首页 > 解决方案 > 如何在循环中使用golang的追加到数组

问题描述

所以我有这个结构:

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 的数组。但我得到这个输出:[� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �]

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

标签: arraysgo

解决方案


您正在以正确的方式附加。问题是您如何将整数转换为字符串,您正在这样做Python。请查看strconv.ItoaGo等效项。


推荐阅读