Golang: I have a map of structs. Why can't I d

2020-02-06 05:37发布

Why do we have to first read the struct, modify it, and then write it back to the map? Am I missing some kind of implied hidden cost in modifying fields of structs in other data structures (like a map or a slice)?

Edit: I realize I can use pointers, but why is this not allowed by Go?

type dummy struct {
    a int
}
x := make(map[int]dummy)
x[1] = dummy{a:1}
x[1].a = 2

标签: go struct
1条回答
够拽才男人
2楼-- · 2020-02-06 06:06

You are storing a struct by value which means that accession of that struct in the map gives you a copy of the value. This is why when you modify it, the struct in the map remains unmutated until you overwrite it with the new copy.

As RickyA pointed out in the comment, you can store the pointer to the struct instead and this allows direct modification of the struct being referenced by the stored struct pointer.

i.e. map[whatever]*struct instead of map[whatever]struct

查看更多
登录 后发表回答