gordonklaus/ineffassign

False Positive when using Defer

Closed this issue · 3 comments

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

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.

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)
}()

Thanks!