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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵