[英]Looping over a slice in Go to create a map [closed]
我正在循环 Go 中的一个切片,该切片由我制作的名为 Product 的结构组成。
我想把这个切片变成 map,这样 Product Id 是键, Product 是值。
这是我创建的结构。
type Product struct {
productID int `json:"prodId"`
Manufacturer string `json:"manufacturer"`
PricePerUnit string `json:"ppu"`
Sku string `json:"sku"`
Upc string `json:"upc"`
QuantityOnHand int `json:"qoh"`
ProductName string `json:"prodName"`
}
这是我创建的 function...
func loadProductMap() (map[int]Product, error) {
fileName := "products.json"
_, err := os.Stat(fileName) //os package with the Stat method checks to see if the file exists
if os.IsNotExist(err) {
return nil, fmt.Errorf("file [%s] does not exist", fileName)
}
file, _ := ioutil.ReadFile(fileName) //reads the file and returns a file and an error; not concerned with the error
productList := make([]Product, 0) //initialize a slice of type Product named productList, length is zero
err = json.Unmarshal([]byte(file), &productList) // unmarshal/decode the json file and map it into the productList slice
if err != nil {
log.Fatal(err)
}
prodMap := make(map[int]Product) //initialize another variable called prodMap and make a map with the map key being an integer and the value being of type Product
fmt.Println(len(productList))
for i := 0; i < len(productList); i++ { //loop over the productList slice
prodMap[productList[i].productID] = productList[i] //the productMap's key will be the productList product's ID at i and it's value will be the actual product (name, manufacturer, cost, etc) at productList[i]
fmt.Println(prodMap)
}
fmt.Println(prodMap)
return prodMap, nil
}
还有更多代码,但除了 for 循环之外,所有代码都可以正常工作。 当我在 for 循环中打印出产品 map 时,它会单独 go 对 productList 中的每个项目(190 个项目)进行处理,但它只会返回一个项目 - 最后一个项目。 我应该以某种方式将每次迭代附加到 map 吗? 我在视频教程旁边进行编码,并拥有教程视频中的源文件,与他们的代码相比,我的代码找不到任何问题......
struct字段productId
没有导出,所以json.Unmarshal
不能设置,你所有的product Ids都是零。 导出它: ProductId
,它应该可以工作。
您的json.Unmarshal
将无法访问您的结构字段productID
。 这是因为productID
是一个意想不到的字段,这意味着它就像结构的私有变量。
您可以更改您的字段productID
-> ProductID
,这会使您的结构字段现在导出(因为变量名称以大写字母开头,它将像其他语言中的公共变量)。 您的json.Unmarshal
现在可以愉快地访问ProductID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.