Hey everybody,
I’ve been working with Go and encountered a scenario the place I have to detect unused variables which were 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 essential
import (
"fmt"
"strconv"
)
func essential() {
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 strains 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 manner you’re certain it’s a totally different variable from the earlier one and it’s only 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 is rarely used (SA4006)