I've been staring at this code and can't figure out the why of its behavior.
package main
import (
"fmt"
)
var i int
func example() int {
defer func() {
fmt.Println("defer")
i = 1
}()
fmt.Println("first")
return i
}
func main() {
fmt.Println(example())
fmt.Println(i)
}
At first, the expected output for me is:
first
defer
1
1
But, as you can see in the playground the actual output is:
first
defer
0
1
Is it a deferred anonymous function behavior? Nope
So, why is it printing 0
?