Skip to content
This repository was archived by the owner on May 9, 2021. It is now read-only.

Commit fb4f8c1

Browse files
dominikhandybons
authored andcommitted
golint: suggest for range when possible
for _ = range and for _, _ = range can be written as for range instead. Change-Id: I6d5e7aecce941260f4a4de294685f99d9ff48c09 GitHub-Last-Rev: 318343f GitHub-Pull-Request: #196 Reviewed-on: https://go-review.googlesource.com/96176 Reviewed-by: Alan Donovan <[email protected]>
1 parent 721e727 commit fb4f8c1

File tree

2 files changed

+21
-10
lines changed

2 files changed

+21
-10
lines changed

lint.go

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1084,20 +1084,25 @@ func (f *file) lintRanges() {
10841084
if !ok {
10851085
return true
10861086
}
1087-
if rs.Value == nil {
1088-
// for x = range m { ... }
1089-
return true // single var form
1090-
}
1091-
if !isIdent(rs.Value, "_") {
1092-
// for ?, y = range m { ... }
1087+
1088+
if isIdent(rs.Key, "_") && (rs.Value == nil || isIdent(rs.Value, "_")) {
1089+
p := f.errorf(rs.Key, 1, category("range-loop"), "should omit values from range; this loop is equivalent to `for range ...`")
1090+
1091+
newRS := *rs // shallow copy
1092+
newRS.Value = nil
1093+
newRS.Key = nil
1094+
p.ReplacementLine = f.firstLineOf(&newRS, rs)
1095+
10931096
return true
10941097
}
10951098

1096-
p := f.errorf(rs.Value, 1, category("range-loop"), "should omit 2nd value from range; this loop is equivalent to `for %s %s range ...`", f.render(rs.Key), rs.Tok)
1099+
if isIdent(rs.Value, "_") {
1100+
p := f.errorf(rs.Value, 1, category("range-loop"), "should omit 2nd value from range; this loop is equivalent to `for %s %s range ...`", f.render(rs.Key), rs.Tok)
10971101

1098-
newRS := *rs // shallow copy
1099-
newRS.Value = nil
1100-
p.ReplacementLine = f.firstLineOf(&newRS, rs)
1102+
newRS := *rs // shallow copy
1103+
newRS.Value = nil
1104+
p.ReplacementLine = f.firstLineOf(&newRS, rs)
1105+
}
11011106

11021107
return true
11031108
})

testdata/range.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,12 @@ func f() {
1616
for y, _ = range m { // MATCH /should omit 2nd value.*range.*equivalent.*for y = range/
1717
}
1818

19+
for _ = range m { // MATCH /should omit values.*range.*equivalent.*for range/
20+
}
21+
22+
for _, _ = range m { // MATCH /should omit values.*range.*equivalent.*for range/
23+
}
24+
1925
// all OK:
2026
for x := range m {
2127
_ = x

0 commit comments

Comments
 (0)