英文:
golang: How to assign a new map to a struct field
问题
我正在迭代一个包含map字段的结构体数组:
type Config struct {
// ... 其他字段
KV map[string]interface{} `json:"kv"`
}
在一个测试文件中,我知道KV
是空的,所以我正在迭代Config
对象的数组,并给它赋予一个新的map:
for _, v := range wrapper.Configs { // 我知道这个数组的长度大于0
newMap := map[string]interface{}{
"key1": "val1",
"key2": "val2",
"key3": "val3",
}
v.KV = newMap // 我先尝试直接赋值,不起作用,然后尝试复制,也不起作用
}
for _, v := range wrapper.Configs {
fmt.Println(v.KV)
}
但是循环结束后,KV
始终为空。
我还尝试过:
for _, v := range wrapper.Configs { // 我知道这个数组的长度大于0
v.KV = make(map[string]interface{})
newMap := map[string]interface{}{
"key1": "val1",
"key2": "val2",
"key3": "val3",
}
for kk, vv := range newMap {
v.KV[kk] = vv
}
}
我还没有找到正确且高效的方法来实现这个,我已经搜索了很多,但是我的搜索词给出了无关的结果。
英文:
I am iterating an array of structs which have a map field:
type Config struct {
// ... some other fields
KV map[string]interface{} `json:"kv"`
}
In a test file, I know KV
is empty, so I am iterating the array of Config
objects and assigning it a new map:
for _, v := range wrapper.Configs { // I know this is length > 0
newMap := map[string]interface{}{
"key1": "val1",
"key2": "val2",
"key3": "val3",
}
v.KV = newMap // I have first tried directly assigning. Didn't work, tried copy - didn't work either
}
for _, v := range wrapper.Configs {
fmt.Println(v.KV)
}
But after the loop, KV
is always empty.
I also tried:
for _, v := range wrapper.Configs { // I know this is length > 0
v.KV = make(map[string]interface{})
newMap := map[string]interface{}{
"key1": "val1",
"key2": "val2",
"key3": "val3",
}
for kk, vv := range newMap {
v.KV[kk] = vv
}
I haven't been able to identify how to do this correctly, and also, efficiently.
Searched quite a bit but my search terms gave me unrelated results.
答案1
得分: 3
假设wrapper.Configs
是一个结构体切片(而不是结构体指针切片),v
是切片中项目的副本,因此更新操作不会改变原始数据。
要使这段代码正常工作,你可以这样写:
for i := range wrapper.Configs {
v := &wrapper.Configs[i]
...
}
英文:
Assuming wrapper.Configs
is a slice of structs (rather than a slice of pointers to structs), v
is a copy of the item in your slice, so updates don't change the originals.
To get this code to work, you can write:
for i := range wrapper.Configs {
v := &wrapper.Configs[i]
...
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论