Hey everybody,
I’ve been working with Go and encountered a state of affairs the place I have to detect unused variables which have been reassigned. Particularly, I’ve code the place an error variable (err
) is reassigned and never checked after the reassignment. Right here’s a simplified instance:
package deal important
import (
"fmt"
"strconv"
)
func important() {
num1, err := strconv.Atoi("123")
if err != nil {
fmt.Printf("Error changing '123': %vn", err)
return
}
num2, err := strconv.Atoi("a")
fmt.Println("Transformed numbers:", num1, num2)
}
In any case you would wish so as to add a test (if) for this variable. For instance add this traces to your code, (1) earlier than the secod Atoi and after that Atoi.
fmt.Printf("%v:%vn", &err, err)
Within the first case as any error occurred, err is nil. and within the second print your err has some worth.:
So it’s higher to test any error inmediately utilizing one thing like
if num2, err := strconv.Atoi("a"); err != nil {
...
}
That approach you might be certain it’s a totally different variable from the earlier one and it is just utilized in that scope, the slender of teh scope, the higher…
There are static code checkers which detect such, for instance golangci-lint and staticcheck
$ golangci-lint run
x.go:15:8: ineffectual project to err (ineffassign)
num2, err := strconv.Atoi("a")
$
$ staticcheck ./...
x.go:15:2: this worth of err isn't used (SA4006)
Thanks! I feel I’ll undertake it since it may be detected by golangci-lint.