为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
开心每一天1111 2023-07-31 15:02:53
我是 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)任何帮助都会非常好
查看完整描述

1 回答

?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

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


查看完整回答
反对 回复 2023-07-31
  • 1 回答
  • 0 关注
  • 73 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信