Golang: I have a map of int to struct. Why can't I directly modify a field in a map value?

huangapple go评论80阅读模式
英文:

Golang: I have a map of int to struct. Why can't I directly modify a field in a map value?

问题

为什么我们必须先读取结构体,修改它,然后再将其写回到映射中?我是否忽略了在修改其他数据结构(如映射或切片)中的结构体字段时存在的某种隐含的隐藏成本?

编辑:
我意识到我可以使用指针,但为什么Go语言不允许这样做?

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

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

答案1

得分: 47

你正在通过值存储一个结构体,这意味着在映射中访问该结构体会得到一个值的副本。这就是为什么当你修改它时,映射中的结构体保持不变,直到你用新的副本覆盖它。

正如RickyA在评论中指出的那样,你可以存储指向结构体的指针,这样可以直接修改被存储结构体指针引用的结构体。

map[whatever]*struct而不是map[whatever]struct

英文:

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

huangapple
  • 本文由 发表于 2016年11月14日 04:47:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/40578646.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定