亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

初始化嵌套結構圖

初始化嵌套結構圖

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條經驗 獲得超4個贊

如果您知道初始值。為什么不這樣做


   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 關注
  • 174 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號