As I know, defer is usually used to close or free resources.
And using defer FUNC ()
inside the block (function) of the code ensures that FUNC ()
will call in case of any return from this block(function) or panic in this block (function).
So - how to explain defer
behavior in this code: (Example):
package main
import (
"fmt"
"errors"
)
func test() error {
err := errors.New("some error")
return err
}
func main() {
if err := test(); err!=nil {
fmt.Println("ERROR EXIT")
return
}
defer fmt.Println("DEFER EXIT")
fmt.Println("NORMAL EXIT")
}
I expected to see this:
ERROR EXIT
DEFER EXIT
But got it:
ERROR EXIT
Where am I wrong?