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

How to Properly Initialize Nested Structs in Go?

Linda Hamilton
Linda HamiltonOriginal
2025-01-03 18:22:39384browse

How to Properly Initialize Nested Structs in Go?

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!

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