How do you initialize the following struct?
type Sender struct { BankCode string Name string Contact struct { Name string Phone string } }
I tried:
s := &Sender{ BankCode: "BC", Name: "NAME", Contact { Name: "NAME", Phone: "PHONE", }, }
Didn't work:
mixture of field:value and value initializers undefined: Contact
I tried:
s := &Sender{ BankCode: "BC", Name: "NAME", Contact: Contact { Name: "NAME", Phone: "PHONE", }, }
Didn't work:
undefined: Contact
Initializing nested Structures struct 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 };
An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).
A structure inside another structure is called nested structure. Consider the following example, struct emp{ int eno; char ename[30]; float sal; float da; float hra; float ea; }e; All the items comes under allowances can be grouped together and declared under a sub – structure as shown below.
You can also create and initialize a struct with a struct literal. An element list that contains keys does not need to have an element for each struct field. Omitted fields get the zero value for that field.
Your Contact
is a field with anonymous struct type. As such, you have to repeat the type definition:
s := &Sender{ BankCode: "BC", Name: "NAME", Contact: struct { Name string Phone string }{ Name: "NAME", Phone: "PHONE", }, }
But in most cases it's better to define a separate type as rob74 proposed.
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