【问题标题】:Looping over a slice in Go to create a map [closed]在 Go 中循环切片以创建地图 [关闭]
【发布时间】:2026-01-28 23:35:01
【问题描述】:

我正在遍历 Go 中的一个切片,该切片由我创建的名为 Product 的结构组成。

我想把这个切片变成一个map,这样Product Id就是key,Product就是value。

这是我创建的结构。

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"`
}

这是我创建的函数...

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 循环中打印出 prod 映射时,它确实会单独检查 productList 中的每一项(190 项),但它只会返回一项 - 最后一项。我应该以某种方式将每次迭代附加到地图上吗?我在视频教程旁边进行编码,并拥有教程视频中的源文件,与他们的代码相比,我的代码找不到任何问题....

【问题讨论】:

标签: for-loop go go-map go-structtag


【解决方案1】:

struct 字段productId 没有导出,所以json.Unmarshal 不能设置它,你所有的产品ID 都是零。导出它:ProductId,它应该可以工作。

【讨论】:

    【解决方案2】:

    您的json.Unmarshal 将无法访问您的结构字段productID。这是因为productID 是一个意想不到的字段,这意味着它就像结构的私有变量。

    您可以更改您的字段productID -> ProductID,这会使您的结构字段现在导出(因为变量名称以大写字母开头,它就像其他语言中的公共变量一样)。您的json.Unmarshal 现在可以愉快地访问ProductID

    【讨论】: