Initializing Nested Structs in Go [duplicate]
When working with nested structs in Go, you may encounter an error if you attempt to initialize the main struct using an interface as the type of the inner struct. To address this issue, there are several approaches you can consider:
Duplicating the Anonymous Struct Type
If the inner struct is an anonymous struct, you can initialize the main struct by explicitly specifying the type of the inner struct again during construction:
type DetailsFilter struct { Filter struct { Name string ID int } } df := DetailsFilter{Filter: struct { Name string ID int }{Name: "myname", ID: 123}}
Initializing After Creation
Alternatively, you can create the main struct with zero values and then assign values to the nested struct afterward:
df := DetailsFilter{} df.Filter.Name = "myname2" df.Filter.ID = 321
Using a Named Anonymous Struct Type
You can avoid the initial error by defining the inner struct as a named type instead of an anonymous struct:
type Filter struct { Name string ID int } type DetailsFilter struct { Filter Filter }
Then you can initialize the main struct as follows:
df := DetailsFilter{Filter: Filter{Name: "myname", ID: 123}}
The above is the detailed content of How to Properly Initialize Nested Structs in Go?. For more information, please follow other related articles on the PHP Chinese website!