Skip to content

Commit 9c737ea

Browse files
committed
Allow no-argument methods in capacity suggestions
1 parent 179a4dc commit 9c737ea

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

pkg/prealloc.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -837,6 +837,11 @@ func hasCall(expr ast.Expr) bool {
837837
// allow cheap pure built-in functions
838838
return true
839839
}
840+
case *ast.SelectorExpr:
841+
// allow argument-less methods
842+
if len(call.Args) == 0 {
843+
return true
844+
}
840845
}
841846
found = true
842847
}

testdata/for.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package test
22

3+
import "bytes"
4+
35
func forInfinite() {
46
var x []int
57
for {
@@ -226,6 +228,14 @@ func forTypeConvert() {
226228
}
227229
}
228230

231+
func forNoArgMethod() {
232+
var buf bytes.Buffer
233+
var x []int // want "Consider preallocating x with capacity buf\\.Len\\(\\)$"
234+
for i := 0; i < buf.Len(); i++ {
235+
x = append(x, i)
236+
}
237+
}
238+
229239
func forMultipleConjunctiveUpperLimits() {
230240
m := 7
231241
n := 6

testdata/range.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package test
22

3-
import "sort"
3+
import (
4+
"bytes"
5+
"sort"
6+
)
47

58
func rangeZero() {
69
var x []int
@@ -182,6 +185,14 @@ func rangeIntTypeConvert() {
182185
}
183186
}
184187

188+
func rangeIntNoArgMethod() {
189+
var buf bytes.Buffer
190+
var x []int // want "Consider preallocating x with capacity buf\\.Len\\(\\)$"
191+
for i := range buf.Len() {
192+
x = append(x, i)
193+
}
194+
}
195+
185196
func rangeMultiple() {
186197
var x []int // want "Consider preallocating x with capacity 5 \\+ n \\+ len\\(s\\) \\+ \\(n \\+ 1 - m\\)$"
187198
for i := range 5 {

0 commit comments

Comments
 (0)