3 ms·
I am not sure capturing variables by reference implements the expected behavior; what would the equivalent C++ code return for this Go example? func a() {
by junke 9y ago
I am not sure capturing variables by reference implements the expected behavior; what would the equivalent C++ code return for this Go example?
func a() {
i := 0
defer fmt.Println(i)
i++
return
}
- JBReefer 9y agoWouldn'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 }