How can I do this:
type A struct {
MemberA string
}
type B struct {
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?
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 initializeMemberA
:The compiler error
says exactly that: there's no
MemberA
as it is still inA
and not inB
. In fact,B
will never haveMemberA
, it will always remain inA
. Being able to accessMemberA
on an instance ofB
is only syntactic sugar.The problem is with declaring the struct A in B. Please specify the name along with declaration, then it works.