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条)

报告相同问题?

悬赏问题

  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程