我的术语可能取消了,所以我使用了一些python术语。
在golang中要做的是迭代具有如下存储值的支柱(这就是我从api中得到的)
[{STOREA 0 0 0} {STOREB 0 0 0} {STOREC 0 0 0} {STORED 0 0 0}]在python中,我会称这为一个dicts列表。
当我在可视代码中的值上悬停时,它声明如下:
字段itemData []struct{代码字符串“json:”“Code”;项目int“json:”float64“json”;float64“json:”价格“;Qty int”json:“Qty”}
package main
// I think this is the right way to interpret what visual code stated
type itemData struct {
Code string `json:"Code"`
Items int `json:"Items"`
Price float64 `json:"Price"`
Qty int `json:"Qty"`
}
//I'm trying to simulate the api response by storing it in a varible like this but I think the [] are an issue and im doing it incorrectly
var storeData = itemData[{STOREA 0 0 0} {STOREB0 0 0} {STOREC 0 0 0} {STORED0 0 0}] // I think the [ ] brackets are causing an issue
//The idea is I can iterate over it like this:
for k,v := range storeData {
fmt.Printf(k,v)
}发布于 2022-03-16 07:20:37
推荐给去切片之旅
然后试试这个:
var storeData = []itemData{{"STOREA", 0, 0, 0}, {"STOREB", 0, 0, 0}, {"STOREC", 0, 0, 0}, {"STORED", 0, 0, 0}}
for k, v := range storeData {
fmt.Println(k, v)
}发布于 2022-03-16 07:25:32
您所做的是一个slice of itemData (struct)。直接使用切片文字来初始化带有值的切片是非常直接的。看起来是这样的:
storeData := []itemData{
{
Code: "STOREA",
Items: 0,
Price: 0,
Qty: 0,
},
{
Code: "STOREB0",
Items: 0,
Price: 0,
},
{
Code: "STOREC",
Items: 0,
Price: 0,
Qty: 0,
},
{
Code: "STORED0",
Items: 0,
Price: 0,
},
}
for i, v := range storeData {
fmt.Printf("index: %d, value: %v\n", i, v)
}https://stackoverflow.com/questions/71493012
复制相似问题