登录
首页 >  Golang >  Go问答

使用指针或索引解析范围内的 rangeValCopy gocritic 消息的方法

来源:stackoverflow

时间:2024-02-16 12:45:24 198浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《使用指针或索引解析范围内的 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))
}

这是 go 演示。

此输出是什么意思以及我该如何执行它所要求的操作?我尝试在每个项目上使用指针,但这似乎没有什么区别。


解决方案


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,
            },
        } 
}

linter 的另一个建议是使用范围在每次迭代时返回的索引值

for i := range products{
   item := []Item{
            {
                //access elements by index directly
                ProductBrand: products[i].ProductBrand,
                ProductName:  products[i].Name,
                ProductType:  products[i].ProductType,
            },
        } 
}

好了,本文到此结束,带大家了解了《使用指针或索引解析范围内的 rangeValCopy gocritic 消息的方法》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>