英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论