Arjun Ajith
Arjun Ajith

Reputation: 1920

How to access golang Struct Array inside another Struct?

How can I access the fields of a Struct Array which is inside another Struct?

My Structs as follows:-

type Company struct {
Id              bson.ObjectId `bson:"_id,omitempty"`
Company_name    string
Admin           UserMinimal
Process         []ProcessItem
}

type ProcessItemMinimal  struct {
Id              bson.ObjectId `bson:"_id,omitempty"`
Process_name    string
Processtype     int64   
}

type ProcessItem  struct{
ProcessItemMinimal  `bson:",inline"`
Sortorder           int64   
}

I need to store some data in []ProcessItem inside Company struct. The data will be like this.

ProcessItem[0]=Process_name:"Enquiry",Processtype:0,Sortorder:0}
ProcessItem[1]=Process_name:"Converted",Processtype:1,Sortorder:1}
ProcessItem[2]={Process_name:"Enquiry",Processtype:1,Sortorder:2}

Upvotes: 0

Views: 713

Answers (1)

ANisus
ANisus

Reputation: 77925

If you are looking for setting the data using composite struct literals, it can be done like this:

company.Process = []ProcessItem{
    ProcessItem{
        ProcessItemMinimal: ProcessItemMinimal{
            Process_name: "Enquiry",
            Processtype:  0,
        },
        Sortorder: 0,
    },
    ProcessItem{
        ProcessItemMinimal: ProcessItemMinimal{
            Process_name: "Converted",
            Processtype:  1,
        },
        Sortorder: 1,
    },
}

You must specify ProcessItemMinimal when creating a struct literal because, as the Specification says:

Promoted fields act like ordinary fields of a struct except that they cannot be used as field names in composite literals of the struct.

Upvotes: 2

Related Questions