How can I do this:
type A struct { MemberA string } type B struct { A A MemberB string }
...
b := B { MemberA: "test1", MemberB: "test2", } fmt.Printf("%+v\n", b)
Compiling that gives me: "unknown B field 'MemberA' in struct literal"
How can I initialize MemberA (from the "parent" struct) when I provide literal struct member values like this?
Initializing nested Structuresstruct person { char name[20]; int age; char dob[10]; }; struct student { struct person info; int rollno; float marks[10]; } struct student student_1 = { {"Adam", 25, 1990}, 101, 90 };
Using designated initializers, a C99 feature which allows you to name members to be initialized, structure members can be initialized in any order, and any (single) member of a union can be initialized. Designated initializers are described in detail in Designated initializers for aggregate types (C only).
A structure or struct in Golang is a user-defined type, which allows us to create a group of elements of different types into a single unit. Any real-world entity which has some set of properties or fields can be represented as a struct. Go language allows nested structure.
While initialization the anonymous struct is only known under its type name (in your case A
). The members and functions associated with the struct are only exported to the outside after the instance exists.
You have to supply a valid instance of A
to initialize MemberA
:
b := B { A: A{MemberA: "test1"}, MemberB: "test2", }
The compiler error
unknown B field 'MemberA' in struct literal
says exactly that: there's no MemberA
as it is still in A
and not in B
. In fact, B
will never have MemberA
, it will always remain in A
. Being able to access MemberA
on an instance of B
is only syntactic sugar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With