I am experimenting with Go and am seeing some unexpected behaviour with deferred functions. Consider the following program that increments a global variable by a given amount.
package main
import "fmt"
var z = 1
func main() {
defer increaseZ(10)
defer fmt.Println("z =", increaseZ(20), "Deferred Value 1")
defer fmt.Println("z =", increaseZ(30), "Deferred Value 2")
fmt.Println("z =", z, "Main Value")
}
func increaseZ(y int) int {
z += y
println("z =", z, "Inside Increase Function")
return z
}
When run in the go playground, this outputs:
z = 21 Inside Increase Function
z = 51 Inside Increase Function
z = 61 Inside Increase Function
z = 51 Main Value
z = 51 Deferred Value 2
z = 21 Deferred Value 1
If I switch the order of the deferred functions, it has another effect:
defer fmt.Println("z =", increaseZ(20), "Deferred Value 1")
defer fmt.Println("z =", increaseZ(30), "Deferred Value 2")
defer increaseZ(10)
Outputs:
z = 21 Inside Increase Function
z = 51 Inside Increase Function
z = 51 Main Value
z = 61 Inside Increase Function
z = 51 Deferred Value 2
z = 21 Deferred Value 1
The Go documentation states:
The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
So arguments being evaluated, may explain why the Main Value returned is 51 and not 61, since the fmt.Println statements are taking increaseZ
as an argument, but defer increaseZ(10)
would not be called until after the main function returns.
However, this does not explain why in the first example the increaseZ(10)
is outputting before main has completed, and after main has completed in the second example.
I would be grateful if anyone could help me understand what is happening here, since this looks like fertile ground for difficult to diagnose bugs further down the line.