Home >Backend Development >Golang >How to Initialize Nested Struct Fields in Go Using Field References?

How to Initialize Nested Struct Fields in Go Using Field References?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-24 12:59:14934browse

How to Initialize Nested Struct Fields in Go Using Field References?

Nested Struct Initialization with Field References

The task is to initialize a nested struct with literal values while setting a field belonging to a parent struct. Here's an example:

type A struct {
    MemberA string
}

type B struct {
    A
    MemberB string
}

Attempts to initialize MemberA directly in a struct literal, as shown below, will fail:

b := B {
    MemberA: "test1",
    MemberB: "test2",
}
fmt.Printf("%+v\n", b)

This results in the error: "unknown B field 'MemberA' in struct literal."

To initialize MemberA correctly, you must provide a valid instance of the parent struct, A, as seen in this code:

b := B {
    A: A{MemberA: "test1"}, // Initialize the parent struct instance
    MemberB: "test2",
}

The compiler error message "unknown B field 'MemberA' in struct literal" indicates that MemberA is not a known field of B directly. Instead, it belongs to the embedded A type. When initializing the B struct, the anonymous A instance is only known under the type name A, and its members are not visible outside the instance until it is created.

The above is the detailed content of How to Initialize Nested Struct Fields in Go Using Field References?. 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