如何在 go 中初始化嵌套结构? [英] How to initialise nested structs in go?

查看:31
本文介绍了如何在 go 中初始化嵌套结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Golang 很陌生,请帮助我.我在结构中定义了一个结构.但是当我尝试初始化主结构时出现错误.

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.

请提出一种初始化 DetailsFilter 的方法.我尝试执行 在 Golang 中初始化嵌套结构 中描述的方法,但即使这是行不通的.

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.

推荐答案

不幸的是,如果结构字段的类型是匿名结构,在构造时你只能通过复制"来初始化它匿名结构类型(再次指定):

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)

输出:

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

输出:

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

Go Playground 上试试.

或者根本不使用匿名结构体作为字段类型,像这样命名类型:

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)

输出(在 Go Playground 上试试):

Output (try it on the Go Playground):

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

这篇关于如何在 go 中初始化嵌套结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆