访问未定义的数组元素的结构类型时出现错误

我是 golang 新手,我有一个如下所示的数据结构


     type ParentIDInfo struct {

    PCOrderID      string         `json:"PCorderId",omitempty"`

    TableVarieties TableVarietyDC `json:"tableVariety",omitempty"`

    ProduceID      string         `json:"PRID",omitempty"`

}


type PCDCOrderAsset struct {

    PcID         string              `json:"PCID",omitempty"`

    DcID         string              `json:"DCID",omitempty"`

    RequiredDate string              `json:"requiredDate",omitempty"`

    Qty          uint64              `json:"QTY",omitempty"`

    OrderID      string              `json:"ORDERID",omitempty"`

    Status       string              `json:"STATUS",omitempty"`

    Produce      string              `json:"Produce",omitempty"`

    Variety      string              `json:"VARIETY",omitempty"`

    Transports   []TransportaionPCDC `json:"Transportaion",omitempty"`

    ParentInfo   []ParentIDInfo        `json:"ParentInfo",omitempty"`

所以我在访问[]ParentIDInfo内的PCOrderID时遇到问题。我在下面尝试过,但收到错误“pcdcorder.ParentInfo.PCOrderID undefined (type []ParentIDInfo has no field or method PCOrderID)”


keyfarmercas = append(keyfarmercas, pcdcorder.ParentInfo.PCOrderID)

任何帮助都会非常好


开心每一天1111
浏览 75回答 1
1回答

潇潇雨雨

PCDCOrderAsset.ParentInfo不是结构体,它没有字段PCOrderID。它是一个切片(元素类型为ParentIDInfo),因此它的元素也是如此,例如pcdcorder.ParentInfo[0].PCOrderID。这是否是你想要的我们无法判断。pcdcorder.ParentInfo[0].PCOrderID给出PCOrderID切片第一个元素的字段。根据您的问题,这可能是也可能不是您想要的。您可能想要附加所有 ID(每个元素一个)。另请注意,如果切片为空(其长度为 0),则会pcdcorder.ParentInfo[0]导致运行时恐慌。您可以通过首先检查其长度并仅在其不为空时对其进行索引来避免这种情况。如果您想添加所有元素的 id,您可以使用循环for来执行此操作,例如:for i := range pcdorder.ParentInfo {     keyfarmercas = append(keyfarmercas, pcdcorder.ParentInfo[i].PCOrderID) }
打开App,查看更多内容
随时随地看视频慕课网APP