When working with nested structs in Golang, initializing the main struct can be tricky. This guide aims to provide a solution to the error encountered when trying to initialize a struct with an embedded anonymous struct as a field.
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"]}}
This code attempts to initialize a DetailsFilter struct with a nested anonymous struct Filter. However, when trying to initialize the Filter field from a map, an error is encountered:
can not use (type interface {}) as type struct in field value : need type assertion
The recommended solution is to avoid initializing the nested anonymous struct during construction. Instead, initialize the zero-valued struct and then assign values to the nested fields:
df := DetailsFilter{} df.Filter.Name = "myname" df.Filter.ID = 123
Another alternative is to name the anonymous struct type and initialize it explicitly:
type Filter struct { Name string ID int } type DetailsFilter struct { Filter Filter } df := DetailsFilter{Filter: Filter{Name: "myname", ID: 123}}
The above is the detailed content of How to Properly Initialize Nested Structs in Golang?. For more information, please follow other related articles on the PHP Chinese website!