为了账号安全,请及时绑定邮箱和手机立即绑定

如何在范围上使用指针或索引来解析 rangeValCopy gocritic 消息

如何在范围上使用指针或索引来解析 rangeValCopy gocritic 消息

Go
森林海 2022-08-15 19:29:07
我在运行 https://golangci-lint.run/ 时收到以下输出:rangeValCopy: each iteration copies 128 bytes (consider pointers or indexing) (gocritic)    for _, v := range products {以下是我正在运行的代码的精简版本:package mainimport (    "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))}这是在围棋操场上。这个输出是什么意思,我该如何做它所要求的?我试图在每个项目上使用指针,但这似乎没有区别。
查看完整描述

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,

            },

        } 

}


查看完整回答
反对 回复 2022-08-15
  • 1 回答
  • 0 关注
  • 192 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号