scopelint checks for unpinned variables in go programs.
Sample problem code like this:
values := []string{"a", "b", "c"}
var funcs []func()
for _, val := range values {
funcs = append(funcs, func() {
fmt.Println(val)
})
}
scoplint
checks find:
Using the variable on range scope "val" in function literal
Using a reference for the variable on range scope "val"
Found 2 lint problems; failing.
The reason is, in Go, the val
variable in the above loop is actually a single variable.
To fix it, there are three ways.
First, you can exclude functional literal check by adding the follow code in .golangci.yml
issues:
exclude:
- Using the variable on range scope .* in functional literal
Second, you can redefine this variable in loop.
values := []string{"a", "b", "c"}
var funcs []func()
for _, val := range values {
val := val
funcs = append(funcs, func() {
fmt.Println(val)
})
}
Third, you can ignore issues for the line, or the block of code, or the file.
var copies []*string
for _, val := range values {
copies = append(copies, &val) //scopelint:ignore
}
var copies []*string
//scopelint:ignore
for _, val := range values {
copies = append(copies, &val)
}
//scopelint:ignore
package pkg