【问题标题】:Initialize nested struct map初始化嵌套结构映射
【发布时间】:2019-02-01 09:50:17
【问题描述】:

问题:

我在另一个结构中有一个结构映射,我想初始化结构的嵌套映射,但显然这是不可能的。

代码:

type Exporter struct {
    TopicsByName      map[string]Topic
}

type Topic struct {
    Name       string
    Partitions map[int32]Partition
}

type Partition struct {
    PartitionID   int32
    HighWaterMark int64
}

// Eventually I want to do something like:
e := Exporter{ TopicsByName: make(map[string]Topic) }
for _, topicName := range topicNames {
  // This does not work because "cannot assign to struct field e.TopicsByName[topicName].Partitions in map"
  e.TopicsByName[topicName].Partitions = make(map[int32]Partition)
}

// I wanted to initialize all these maps so that I can do
e.TopicsByName[x.TopicName].Partitions[x.PartitionID] = Partition{...}

我不明白为什么我不能初始化上面的嵌套结构映射。用结构嵌套映射作为值有那么糟糕吗?我该如何解决这个问题?

【问题讨论】:

  • 在将结构插入地图之前对其进行初始化。

标签: go struct


【解决方案1】:

无法分配给映射值中的字段。解决方法是 将结构值分配给映射值:

for _, topicName := range []string{"a"} {
    e.TopicsByName[topicName] = Topic{Partitions: make(map[int32]Partition)}
}

【讨论】:

    【解决方案2】:

    你可以像你期望的那样初始化它:

    e := Exporter{
        TopicsByName: map[string]Topic{
            "my-topic": Topic{
                Name: "my-topic",
                Partitions: map[int32]Partition{
                    int32(1): Partition{
                        PartitionID:   int32(1),
                        HighWaterMark: int64(199),
                    },
                },
            },
        },
    }
    

    这不是直接回答问题,因为您想遍历主题列表,但如果这用于 kafka 测试,我强烈推荐上面更详细/文字格式。

    https://play.golang.org/p/zm3A7CIvbyu

    【讨论】:

      【解决方案3】:

      如果您知道初始值。为什么不这样做呢

         val := `
           {
               "topics_by_name": {
                   "name1": {
                       "name":"topicname1",
                       "partions": {
                           1: {
                               "partion_id":1,
                               "high_water_mark":12,
                           },
                           2: {} 
                       }
                    },
                   "name2": {}
               }
           }
          `
      func main() {
         var m map[string]interface{}
         // if m has be well designed, use your designed map is better
         // init
         json.Unmarshal(val, &m)
      }
      

      【讨论】:

        猜你喜欢
        • 2021-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多