初始化嵌套的结构图

时间:2019-01-31 16:34:12

标签: go struct

问题:

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

代码:

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{...}

我不明白为什么我不能初始化上面的嵌套结构图。嵌套带有struct作为值的映射是否太糟糕了?我该如何解决?

3 个答案:

答案 0 :(得分:1)

无法在地图值中分配给字段。解决方法是 为地图值分配一个struct值:

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

答案 1 :(得分:0)

您可以按期望的方式对其进行初始化:

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

答案 2 :(得分:0)

如果您知道初始值。为什么不喜欢

   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)
}
相关问题