dictionary - golang : How to assign a new map to a struct field

标签 dictionary go

我正在迭代具有映射字段的结构数组:

type Config struct {
  // ... some other fields
  KV map[string]interface{} `json:"kv"`
}

在测试文件中,我知道KV是空的,所以我正在迭代 Config 的数组对象并为其分配新 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)
  }

但是在循环之后,KV始终为空。

我也尝试过:

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
    } 

我无法确定如何正确且有效地执行此操作。

搜索了很多,但我的搜索词给了我不相关的结果。

最佳答案

假设wrapper.Configs是一个结构体 slice (而不是指向结构体的指针 slice ),v是 slice 中项目的副本,因此更新不要改变原来的。

要使此代码正常工作,您可以编写:

for i := range wrapper.Configs {
    v := &wrapper.Configs[i]
    ...
}

关于dictionary - golang : How to assign a new map to a struct field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70610629/

相关文章:

python - 在 Python 3.6 中使用 setdefault 使用来自两个不同文件的信息显示(名称、id 和频率计数)

java - 实现 HashMap<Integer, ArrayList<String>> 时如何为每个键提供不同的数组列表

go - 无符号整数溢出

go - 为什么很多golang项目直接从GitHub导入?

go - ListObjectsV2 api 调用是否在 Google Cloud Storage 中实现?

mongodb - 禁用 Go mongo bson map 中的某些字段

dictionary - 如何从 es6 Map 或 Set 中获取随机项目

python-3.x - 组合使用 itertools 和 zip 从两个不同长度的列表创建字典时出现问题

java - 使用唯一属性检索枚举值

go - 如何将stdout的输出转换为golang中的字符串