dqhr76378 2016-02-24 07:47
浏览 242
已采纳

如何在另一个Struct中访问golang 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}
  • 写回答

1条回答 默认 最新

  • doubo1871 2016-02-24 08:05
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?