首页 > 解决方案 > 访问未定义的数组元素的结构类型时出错(类型 []ParentIDInfo 没有字段或方法 PCOrderID)

问题描述

我是 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)

任何帮助都会很好

提前致谢

标签: gostructslice

解决方案


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

推荐阅读