4 ms·
Wouldn't this work by reference? The referenced value would be the same in both contexts. Honestly, am I missing something?
by JBReefer 9y ago
Wouldn't this work by reference? The referenced value would be the same in both contexts.
Honestly, am I missing something?
- Vendan 9y agoGo prints 0: https://play.golang.org/p/kdi60DOln- https://play.golang.org/p/kdi60DOln-
- parenthephobia 9y agoThe syntax of defer is a function call, but it isn't called like a normal function: the arguments are evaluated at the time the defer is encountered, and then the function is called later. That's one reason why defer is very often called with an anonymous function, so that variables can be captured. So, the version that prints 1 is func a() { i := 0 defer func(){ fmt.Println(i) }() i++ return }