【问题标题】:How to use golang's append to an array in a loop [duplicate]如何在循环中使用golang的追加到数组[重复]
【发布时间】:2020-04-04 09:26:02
【问题描述】:

所以我有这个结构:

type AllShipments struct {
    Shipments []struct {
        ShipmentID    int       `json:"shipmentId"`
        ShipmentDate  time.Time `json:"shipmentDate"`
        ShipmentItems []struct {
            OrderItemID string `json:"orderItemId"`
            OrderID     string `json:"orderId"`
        } `json:"shipmentItems"`
        Transport struct {
            TransportID int `json:"transportId"`
        } `json:"transport"`
    } `json:"shipments"`
}

我想获得一个仅包含 shippingID 值的列表,因为我需要它来进行 API 调用以获取单个货件的具体详细信息。然后我可以在我的 API 调用中循环它。

在 Python 中我这样做了:

# Create shipments dataframe
df_shipments = json_normalize(full_df['shipments'], 'shipmentItems', columns)

# Turn into list so we can loop over the shipmentId property in our API call to get more detailed information
ship_list = df_shipments['shipmentId'].tolist()

非常强大,只有两行代码。但是很多魔法正在发生。我想对 Golang 做同样的事情。从文档和一些搜索中我想出了这个想法:

var shipmentList []string
for _, v := range t.Shipments {
    shipmentList = append(shipmentList, string(v.ShipmentID))
}

那么shipmentList 应该返回一个包含所有货件ID 的数组。但我得到了这个输出:[� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �]

有人可以澄清发生了什么以及为什么我会得到这个结果吗?以及如何得到我想要的预期结果?

【问题讨论】:

  • 不应将shipmentList 的类型设为int

标签: arrays go


【解决方案1】:

您以正确的方式追加。问题是你如何将整数转换为字符串,你是用Python 的方式来做的。请查看 strconv.Itoa 以获取 Go 等效项。

【讨论】:

  • 谢谢你,这很好用!
猜你喜欢
  • 1970-01-01
  • 2020-09-21
  • 2014-11-19
  • 2022-01-25
  • 2020-02-21
  • 1970-01-01
  • 1970-01-01
  • 2020-04-04
  • 1970-01-01
相关资源
最近更新 更多