Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize nested struct definition

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 
like image 342
Kiril Avatar asked Nov 11 '14 14:11

Kiril


People also ask

How do you initialize a nested struct?

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

What is struct initialization?

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

What is a nested struct?

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.

Can you initialize in struct?

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.


1 Answers

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.

like image 75
Ainar-G Avatar answered Sep 24 '22 04:09

Ainar-G