From 7d5d00328e4e9b97d911d6540d4715825e778869 Mon Sep 17 00:00:00 2001 From: ckaznocha Date: Sat, 9 Nov 2024 15:24:29 -0800 Subject: [PATCH] Add note about scopes on assignment --- intrange.go | 13 ++++++++++++- testdata/main.go | 6 ++++++ testdata/main.go.golden | 6 ++++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/intrange.go b/intrange.go index 4d3430e..6ebd668 100644 --- a/intrange.go +++ b/intrange.go @@ -79,6 +79,8 @@ func checkForStmt(pass *analysis.Pass, forStmt *ast.ForStmt) { return } + initAssign := init.Tok == token.ASSIGN + if len(init.Lhs) != 1 || len(init.Rhs) != 1 { return } @@ -229,6 +231,15 @@ func checkForStmt(pass *analysis.Pass, forStmt *ast.ForStmt) { return } + if initAssign { + pass.Report(analysis.Diagnostic{ + Pos: forStmt.Pos(), + Message: msg + "\nBecause the key is not part of the loop's scope, take care to consider side effects.", + }) + + return + } + rangeX := operandToString(pass, initIdent, operand) pass.Report(analysis.Diagnostic{ @@ -523,7 +534,7 @@ func operandToString(pass *analysis.Pass, i *ast.Ident, operand ast.Expr) string return s } - if len(s) > 2 && s[len(s)-1:] == ")" { + if len(s) > 2 && s[len(s)-1] == ')' { return s } diff --git a/testdata/main.go b/testdata/main.go index f017619..06b2316 100644 --- a/testdata/main.go +++ b/testdata/main.go @@ -335,3 +335,9 @@ func issue27() { func notLen(any) int { return 0 } + +func issue33() { + var i int + for i = 0; i < 10; i++ { // want `for loop can be changed to use an integer range \(Go 1\.22\+\)\nBecause the key is not part of the loop's scope, take care to consider side effects.` + } +} diff --git a/testdata/main.go.golden b/testdata/main.go.golden index 48501eb..da98ccf 100644 --- a/testdata/main.go.golden +++ b/testdata/main.go.golden @@ -335,3 +335,9 @@ func issue27() { func notLen(any) int { return 0 } + +func issue33() { + var i int + for i = 0; i < 10; i++ { // want `for loop can be changed to use an integer range \(Go 1\.22\+\)\nBecause the key is not part of the loop's scope, take care to consider side effects.` + } +}