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 linux下点对点协议连接2个USB串口的硬件流量控制问题
  • ¥15 SQL数据自动生成问题
  • ¥15 设密码后无法访问他人的共享文件
  • ¥15 浏览器打不开学校网页
  • ¥100 android开发打不开相册,不弹出授权信息,请问怎么解决?
  • ¥15 我想通过python处理sybase IQ库的一些数据,但是不知道sybase IQ库怎么连接,之前连接都是用linux上的 dbisql
  • ¥15 安装llama-cpp-python==0.1.83失败
  • ¥20 管道轴向耦合水击问题
  • ¥60 补全networkx TODO部分。
  • ¥15 有内推吗,云计算linux运维方向