如何在 Go 中更新地图值 [英] How to update map values in Go
问题描述
我想构建一个带有字符串键和结构值的映射,我可以用它来更新映射键标识的映射中的结构值.
I want to build a map with string key and struct value with which I'm able to update struct value in the map identified by map key.
I've tried this and this which doesn't give me desired output.
我真正想要的是:
Received ID: D1 Value: V1
Received ID: D2 Value: V2
Received ID: D3 Value: V3
Received ID: D4 Value: V4
Received ID: D5 Value: V5
Data key: D1 Value: UpdatedData for D1
Data key: D2 Value: UpdatedData for D2
Data key: D3 Value: UpdatedData for D3
Data key: D4 Value: UpdatedData for D4
Data key: D5 Value: UpdatedData for D5
Data key: D1 Value: UpdatedData for D1
Data key: D2 Value: UpdatedData for D2
Data key: D3 Value: UpdatedData for D3
Data key: D4 Value: UpdatedData for D4
Data key: D5 Value: UpdatedData for D5
推荐答案
您不能更改与映射中的键关联的值,只能重新分配值.
You can't change values associated with keys in a map, you can only reassign values.
这给你留下了两种可能性:
This leaves you 2 possibilities:
在地图中存储指针,因此您可以修改指向的对象(不在地图数据结构内).
Store pointers in the map, so you can modify the pointed object (which is not inside the map data structure).
存储结构体值,但修改时需要重新赋值给key.
Store struct values, but when you modify it, you need to reassign it to the key.
1.使用指针
在地图中存储指针:dataManaged := map[string]*Data{}
当你填充"地图时,你不能使用循环的变量,因为它在每次迭代中都会被覆盖.而是制作它的副本,并存储该副本的地址:
When you "fill" the map, you can't use the loop's variable, as it gets overwritten in each iteration. Instead make a copy of it, and store the address of that copy:
for _, v := range dataReceived {
fmt.Println("Received ID:", v.ID, "Value:", v.Value)
v2 := v
dataManaged[v.ID] = &v2
}
输出符合预期.在 Go Playground 上试试.
Output is as expected. Try it on the Go Playground.
坚持在地图中存储结构值:dataManaged := map[string]Data{}
Sticking to storing struct values in the map: dataManaged := map[string]Data{}
迭代键值对将为您提供值的副本.所以在你修改了值之后,重新赋值:
Iterating over the key-value pairs will give you copies of the values. So after you modified the value, reassign it back:
for m, n := range dataManaged {
n.Value = "UpdatedData for " + n.ID
dataManaged[m] = n
fmt.Println("Data key:", m, "Value:", n.Value)
}
在 Go Playground 上试试这个.
这篇关于如何在 Go 中更新地图值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!