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

How to Properly Initialize Nested Structs in Go?

Linda Hamilton
Release: 2025-01-03 18:22:39
Original
320 people have browsed it

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}}
Copy after login

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
Copy after login

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
}
Copy after login

Then you can initialize the main struct as follows:

df := DetailsFilter{Filter: Filter{Name: "myname", ID: 123}}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template