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

问题描述

您好,我对Golang很新,请帮助我。我在结构体中定义了一个结构体。但是当我尝试初始化主结构时出现错误。

 类型DetailsFilter结构{
Filter结构{
名称字符串
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]}}

我得到的错误是:无法使用(type interface {})作为字段值中的类型struct:need type assertion。

请建议一种初始化DetailsFilter的方法。
我尝试了。

命名匿名结构类型



或者不要使用匿名结构作为字段类型,命名类型是这样的:

 类型Filter结构{
名称字符串
ID int


类型DetailsFilter结构{
Filter Filter
}

然后您可以简单地初始化它:

  df:= DetailsFilter {Filter:Filter {名称:myname,ID:123}} 
fmt.Printf(%+ v \ n,df)

输出(在上试用):

  {过滤器:{Name:myname ID:123}} 


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.

解决方案

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\n", 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\n", df)

Output (try it on the Go Playground):

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

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

05-27 07:05
查看更多