Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nested struct initialization literals

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?

like image 817
Brad Peabody Avatar asked Oct 11 '13 19:10

Brad Peabody


People also ask

How do you initialize a nested struct?

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 };

Can struct have Initializers?

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).

How do I declare a nested struct in Golang?

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.


1 Answers

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.

like image 88
nemo Avatar answered Oct 19 '22 05:10

nemo