douci2015 2015-05-07 13:43
浏览 25
已采纳

如何在go中初始化嵌套结构? [重复]

This question already has an answer here:

Hi I am very new to Golang, please help me. I have defined a struct inside a struct. But I get an error when I try to initialise the main struct.

type DetailsFilter struct {
  Filter struct {
    Name    string        
    ID      int                           
  } 
}

var M map[string]interface{}
M = make(map[string]interface{})
M["Filter"] = map[string]interface{}{"Name": "XYZ", "ID": 5}
var detailsFilter = DetailsFilter{Filter: M["Filter"]}}

The error I get is : can not use (type interface {}) as type struct in field value : need type assertion.

Please suggest a way to initialise DetailsFilter. I tried doing the method described in Initialize a nested struct in Golang, but even this is not working.

</div>
  • 写回答

2条回答 默认 最新

  • doufubu2518 2015-05-07 15:06
    关注

    Unfortunately if the type of a struct field is an anonymous struct, at construction time you can only initialize it by "duplicating" the anonymous struct type (specifying it again):

    type DetailsFilter struct {
        Filter struct {
            Name string
            ID   int
        }
    }
    
    df := DetailsFilter{Filter: struct {
        Name string
        ID   int
    }{Name: "myname", ID: 123}}
    fmt.Println(df)
    

    Output:

    {Filter:{Name:myname ID:123}}
    

    Shorter Alternative

    So instead I recommend not to initialize it at construction, but rather after the zero-valued struct has been created, like this:

    df = DetailsFilter{}
    df.Filter.Name = "myname2"
    df.Filter.ID = 321
    fmt.Printf("%+v
    ", df)
    

    Output:

    {Filter:{Name:myname2 ID:321}}
    

    Try it on the Go Playground.

    Naming the anonymous struct type

    Or don't use anonymous struct as field type at all, name the type like this:

    type Filter struct {
        Name string
        ID   int
    }
    
    type DetailsFilter struct {
        Filter Filter
    }
    

    And then you can simply initialize it like this:

    df := DetailsFilter{Filter: Filter{Name: "myname", ID: 123}}
    fmt.Printf("%+v
    ", df)
    

    Output (try it on the Go Playground):

    {Filter:{Name:myname ID:123}}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题