Golang:我有一张 int 映射到结构体.为什么我不能直接修改地图值中的字段? [英] Golang: I have a map of int to struct. Why can't I directly modify a field in a map value?

查看:17
本文介绍了Golang:我有一张 int 映射到结构体.为什么我不能直接修改地图值中的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们要先读取struct,修改它,然后再写回map?在修改其他数据结构(如地图或切片)中的结构字段时,我是否遗漏了某种隐含的隐藏成本?

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)?

我意识到我可以使用指针,但是 为什么 Go 不允许这样做?

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

推荐答案

您正在按值存储结构,这意味着在映射中访问该结构会为您提供该值的副本.这就是为什么当你修改它时,映射中的结构保持不变,直到你用新副本覆盖它.

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.

正如 RickyA 在评论中指出的那样,您可以改为存储指向结构的指针,这允许直接修改由存储的结构指针引用的结构.

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.

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

这篇关于Golang:我有一张 int 映射到结构体.为什么我不能直接修改地图值中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆