猿问

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

我在运行 https://golangci-lint.run/ 时收到以下输出:

rangeValCopy: each iteration copies 128 bytes (consider pointers or indexing) (gocritic)

    for _, v := range products {

以下是我正在运行的代码的精简版本:


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))

}

这是在围棋操场上

这个输出是什么意思,我该如何做它所要求的?我试图在每个项目上使用指针,但这似乎没有区别。


森林海
浏览 193回答 1
1回答

三国纷争

linter 试图告诉你的是,通过使用 range 的方式使用它,每次你获得一个新元素时,它都不会直接从集合中返回一个元素,而是该元素的新副本。linter 建议了两种方法:将切片更改为指向结构的指针切片,这样 for 循环的每次迭代都将获得对元素的引用,而不是完整的结构副本。vvar products []*ProductDatum//fill products slicevar orderLinesItem []Itemfor _, 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,            },        } }
随时随地看视频慕课网APP

相关分类

Go
我要回答