Home >Backend Development >Golang >How to Properly Initialize Embedded Structs in Go?

How to Properly Initialize Embedded Structs in Go?

DDD
DDDOriginal
2024-12-27 18:24:15415browse

How to Properly Initialize Embedded Structs in Go?

How to Initialize Embedded structs in Golang

In Go, it is possible to define structs within other structs to create nested data structures. However, initializing these nested structs can present a challenge.

Consider the following example:

type DetailsFilter struct {
  Filter struct {
    Name    string        
    ID      int                           
  } 
}

To initialize the DetailsFilter struct with an embedded Filter struct, you may encounter an error if you try to assign a generic map to the Filter field.

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 you will receive is: "can not use (type interface {}) as type struct in field value : need type assertion."

The reason for this error is that an anonymous struct field, as used here for Filter, requires the exact type to be specified during initialization. You can solve this by explicitly defining the type of the Filter field within the anonymous struct:

type DetailsFilter struct {
  Filter struct {
    Name    string        
    ID      int                           
  } 
}

df := DetailsFilter{Filter: Filter{Name: "XYZ", ID: 5}}

Alternatively, you can choose not to use an anonymous struct for Filter and instead give it a named type:

type Filter struct {
  Name    string
  ID      int
}

type DetailsFilter struct {
  Filter Filter
}

df := DetailsFilter{Filter: Filter{Name: "XYZ", ID: 5}}

Both methods will allow you to initialize the DetailsFilter struct with the nested Filter struct.

The above is the detailed content of How to Properly Initialize Embedded Structs in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn