go - 访问未定义的数组元素的结构类型时出错(类型 []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)
任何帮助都会很好
提前致谢
解决方案
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)
}
推荐阅读
- python - 为什么 LDA gensim 实现需要语料库和字典?
- postgresql - 为什么 Spring Data 不支持返回实体来修改查询?
- c - 指针数组 - 在更改先前保存的内容值的同一位置创建临时数组
- ios - 使用 puckettunnel 提供程序 (nsextensionprincipalclass) 的实现创建 SDK
- php - 在模型 [App\Team] laravel 6 上调用未定义的关系 [users]
- qt - Qt/QML:如何在 QML 中双向同步 ScrollView?
- shopify - 修改 Shopify 搜索 - 显示产品变体,正确分页
- javascript - 如何为我的选择元素和按钮重构事件侦听器?
- python - 为什么我有来自 Openweathermap JSON 和 PyOWM 库的不同 api 响应?
- yaml - 如何在 yaml 文件中找到错误?