1 回答

TA貢獻1804條經驗 獲得超7個贊
linter 試圖告訴你的是,通過使用 range 的方式使用它,每次你獲得一個新元素時,它都不會直接從集合中返回一個元素,而是該元素的新副本。linter 建議了兩種方法:將切片更改為指向結構的指針切片,這樣 for 循環的每次迭代都將獲得對元素的引用,而不是完整的結構副本。v
var products []*ProductDatum
//fill products slice
var orderLinesItem []Item
for _, v := range products{
//here v is a pointer instead of a full copy of a struct.
//Go dereferences the pointer automatically therefore you don't have to use *v
item := []Item{
{
ProductBrand: v.ProductBrand,
ProductName: v.Name,
ProductType: v.ProductType,
},
}
}
來自 linter 的另一個建議是使用范圍在每次迭代時返回的索引值
for i := range products{
item := []Item{
{
//access elements by index directly
ProductBrand: products[i].ProductBrand,
ProductName: products[i].Name,
ProductType: products[i].ProductType,
},
}
}
- 1 回答
- 0 關注
- 187 瀏覽
添加回答
舉報