亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在范圍上使用指針或索引來解析 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 關注
  • 187 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號