Hello everyone,
I’ve been working with Go and encountered a situation where I need to detect unused variables that have been reassigned. Specifically, I have code where an error variable (err
) is reassigned and not checked after the reassignment. Here’s a simplified example:
package main
import (
"fmt"
"strconv"
)
func main() {
num1, err := strconv.Atoi("123")
if err != nil {
fmt.Printf("Error converting '123': %v\n", err)
return
}
num2, err := strconv.Atoi("a")
fmt.Println("Converted numbers:", num1, num2)
}
In any case you would need to add a check (if) for this variable. For example add this lines to your code, (1) before the secod Atoi and after that Atoi.
fmt.Printf("%v:%v\n", &err, err)
In the first case as any error happened, err is nil. and in the second print your err has some value.:
So it is better to check any error inmediately using something like
if num2, err := strconv.Atoi("a"); err != nil {
...
}
That way you are sure it is a different variable from the previous one and it is only used in that scope, the narrow of teh scope, the better…
There are static code checkers which detect such, for example golangci-lint and staticcheck
$ golangci-lint run
x.go:15:8: ineffectual assignment to err (ineffassign)
num2, err := strconv.Atoi("a")
$
$ staticcheck ./...
x.go:15:2: this value of err is never used (SA4006)
@Helmut_Wais
Thank you! I think I’ll adopt it since it can be detected by golangci-lint.