False Positive when using Defer
Closed this issue · 3 comments
probably-not commented
Example Code:
package main
import "fmt"
func main() {
ok := true
defer fmt.Println(ok)
err := someOperation()
if err != nil {
ok = false
return
}
}
func someOperation() error {
return fmt.Errorf("Oh no!")
}
Running ineffassign
returns ineffectual assignment to ok
probably-not commented
The expected result here is no errors, since my defer statement here uses the ok
variable, so when I set it and then return, it will be used.
gordonklaus commented
Actually, this is not a false positive. Try running your code. You will see that the assignment ok = false
has no effect. This is because the arguments to a deferred function call are evaluated at the defer
statement — only the function call itself is deferred.
To get the behavior you desire, change the defer to:
defer func() {
fmt.Println(ok)
}()
probably-not commented
Thanks!