为了账号安全,请及时绑定邮箱和手机立即绑定

初始化嵌套结构图

初始化嵌套结构图

Go
呼唤远方 2023-06-05 16:54:09
问题:我在另一个结构中有一个结构映射,我想初始化结构的嵌套映射,但显然这是不可能的。代码: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 doe.TopicsByName[x.TopicName].Partitions[x.PartitionID] = Partition{...}我不明白为什么我不能初始化上面的嵌套结构映射。嵌套以结构体为值的地图有那么糟糕吗?我怎样才能解决这个问题?
查看完整描述

3 回答

?
蛊毒传说

TA贡献1895条经验 获得超3个赞

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

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


查看完整回答
反对 回复 2023-06-05
?
有只小跳蛙

TA贡献1824条经验 获得超8个赞

您可以像预期的那样初始化它:


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


查看完整回答
反对 回复 2023-06-05
?
Helenr

TA贡献1780条经验 获得超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)

}


查看完整回答
反对 回复 2023-06-05
  • 3 回答
  • 0 关注
  • 99 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信