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 关注
- 192 浏览
添加回答
举报