0

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}

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

"You must specify ProcessItemMinimal when creating a struct literal" how to do that? Getting an error "unknown ProcessItem field 'ProcessItemMinimal' in struct literal"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.