运行https://golangci-lint.run/时得到以下输出:
rangeValCopy: each iteration copies 128 bytes (consider pointers or indexing) (gocritic)
for _, v := range products {
Run Code Online (Sandbox Code Playgroud)
这是我正在运行的代码的精简版本:
package main
import (
"fmt"
"encoding/json"
)
type Application struct {
ProductData []ProductDatum
}
type ProductDatum struct {
Name string
ProductBrand string
ProductType string
}
type Item struct {
ProductBrand string
ProductName string
ProductType string
}
func main() {
appl := Application{
ProductData: []ProductDatum{
{
Name: "Baz",
ProductBrand: "Foo",
ProductType: "Bar",
},
},
}
products := appl.ProductData
var orderLinesItem []Item
for _, v := range products {
item := []Item{
{
ProductBrand: v.ProductBrand,
ProductName: v.Name,
ProductType: v.ProductType,
},
}
orderLinesItem = append(orderLinesItem, item...)
}
body, _ := json.Marshal(orderLinesItem)
fmt.Println(string(body))
}
Run Code Online (Sandbox Code Playgroud)
这是围棋游乐场。
此输出是什么意思以及我该如何执行它的要求?我尝试在每个项目上使用指针,但这似乎没有什么区别。
Pab*_*res 15
linter 试图告诉您的是,通过使用 range 的方式,每次获得新元素时,v它不会直接从集合中返回元素,而是该元素的新副本。linter 建议两种方法:要么将切片更改为结构体指针的切片,这样 for 循环的每次迭代都会获得对元素的引用,而不是完整的结构体副本
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,
},
}
}
Run Code Online (Sandbox Code Playgroud)
linter 的另一个建议是使用范围在每次迭代中返回的索引值
for i := range products{
item := []Item{
{
//access elements by index directly
ProductBrand: products[i].ProductBrand,
ProductName: products[i].Name,
ProductType: products[i].ProductType,
},
}
}
Run Code Online (Sandbox Code Playgroud)