Newbie question

185 views
Skip to first unread message

Daniel Jankins

unread,
Jan 10, 2023, 9:43:35 AM1/10/23
to golang-nuts
Hi,

Why can you update a value in a map struct?

 // UnaddressableFieldAssign occurs when trying to assign to a struct field
	// in a map value.
	//
	// Example:
	//  func f() {
	//  	m := make(map[string]struct{i int})
	//  	m["foo"].i = 42
	//  }
I am reading a yaml file and want to change some values in the struct.
Thank s
--
DanJ

wagner riffel

unread,
Jan 10, 2023, 10:32:38 AM1/10/23
to Daniel Jankins, golang-nuts
On 1/10/23 11:42, Daniel Jankins wrote:
> Hi,
>
> Why can you update a value in a map struct?
>

Sort answer, because m["foo"] is not addressable, but you can have the
desired behavior using a temp variable:

func f() {
m := make(map[string]struct{ i int })
x := m["foo"]
x.i = 42
m["foo"] = x
}

BR.
-- w

Daniel Jankins

unread,
Jan 10, 2023, 10:33:17 AM1/10/23
to wagner riffel, golang-nuts
Thanks! 
Reply all
Reply to author
Forward
0 new messages