Skip to content

Commit d4fbc92

Browse files
authored
fix issue #637 (#638)
1 parent baa70eb commit d4fbc92

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

rule/range-val-in-closure.go

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,15 +87,25 @@ func (w rangeValInClosure) Visit(node ast.Node) ast.Visitor {
8787
if !ok {
8888
return w
8989
}
90+
9091
if lit.Type == nil {
9192
// Not referring to a variable (e.g. struct field name)
9293
return w
9394
}
94-
ast.Inspect(lit.Body, func(n ast.Node) bool {
95+
96+
var inspector func(n ast.Node) bool
97+
inspector = func(n ast.Node) bool {
98+
kv, ok := n.(*ast.KeyValueExpr)
99+
if ok {
100+
// do not check identifiers acting as key in key-value expressions (see issue #637)
101+
ast.Inspect(kv.Value, inspector)
102+
return false
103+
}
95104
id, ok := n.(*ast.Ident)
96105
if !ok || id.Obj == nil {
97106
return true
98107
}
108+
99109
for _, v := range vars {
100110
if v.Obj == id.Obj {
101111
w.onFailure(lint.Failure{
@@ -106,6 +116,7 @@ func (w rangeValInClosure) Visit(node ast.Node) ast.Visitor {
106116
}
107117
}
108118
return true
109-
})
119+
}
120+
ast.Inspect(lit.Body, inspector)
110121
return w
111122
}

testdata/range-val-in-closure.go

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,14 +24,26 @@ func foo() {
2424

2525
for i, newg := range groups {
2626
go func(newg int) {
27-
newg.run(m.opts.Context,i) // MATCH /loop variable i captured by func literal/
27+
newg.run(m.opts.Context, i) // MATCH /loop variable i captured by func literal/
2828
}(newg)
2929
}
3030

3131
for i, newg := range groups {
3232
newg := newg
3333
go func() {
34-
newg.run(m.opts.Context,i) // MATCH /loop variable i captured by func literal/
34+
newg.run(m.opts.Context, i) // MATCH /loop variable i captured by func literal/
35+
}()
36+
}
37+
}
38+
39+
func issue637() {
40+
for key := range m {
41+
myKey := key
42+
go func() {
43+
println(t{
44+
key: myKey,
45+
otherField: (10 + key), // MATCH /loop variable key captured by func literal/
46+
})
3547
}()
3648
}
3749
}

0 commit comments

Comments
 (0)