I have a question about golang defer: Is golang defer statement execute before or after return statement?
I have read Defer_statements. But I do not got the answer.
I made a simple test:
func test1() (x int) {
defer fmt.Printf("in defer: x = %d\n", x)
x = 7
return 9
}
func test2() (x int) {
defer func() {
fmt.Printf("in defer: x = %d\n", x)
}()
x = 7
return 9
}
func test3() (x int) {
x = 7
defer fmt.Printf("in defer: x = %d\n", x)
return 9
}
func main() {
fmt.Println("test1")
fmt.Printf("in main: x = %d\n", test1())
fmt.Println("test2")
fmt.Printf("in main: x = %d\n", test2())
fmt.Println("test3")
fmt.Printf("in main: x = %d\n", test3())
}
In test1()
, using Printf
to print x after defer.
In test2()
, using a anonymous function to print x after defer.
In test3()
, using Printf
to print x after defer, but defer after x = 7
.
But the result is:
test1
in defer: x = 0
in main: x = 9
test2
in defer: x = 9
in main: x = 9
test3
in defer: x = 7
in main: x = 9
So, is any one can explain: 1. why got this result? why test1 prints 0, test2 print9, test3 prints 7. 2. is defer statement excutes after return or before return?
Thanks a lot.
Thanks @dev.bmax @Tranvu Xuannhat @rb16. With your help, I found the key explanation from Defer_statements.
Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked.
We can break up defer ...
into three parts.
I made a new test4 to explain.
func test4() (x int) {
defer func(n int) {
fmt.Printf("in defer x as parameter: x = %d\n", n)
fmt.Printf("in defer x after return: x = %d\n", x)
}(x)
x = 7
return 9
}
In test4,
func(n int)(0)
onto stack.func(n int)(0)
after return 9
, n in fmt.Printf("in defer x as parameter: x = %d\n", n)
has been evaluated, x in fmt.Printf("in defer x after return: x = %d\n", x)
will be evaluated now, x is 9。So, got the result:
test4
in defer x as parameter: x = 0
in defer x after return: x = 9
in main: x = 9
As per the documentation of defer
at golang.org,
Go's defer statement schedules a function call (the deferred function) to be run immediately before the function executing the defer returns.
The arguments to the defer statement are evaluated first, then moved to the defer stack and then executed before the enclosing function returns.
Example 1:
Syntax 1:
func display() (x int) {
x = 10
defer func() {
fmt.Println(x)
}()
return 5
}
The above code can be re-written as,
Syntax 2:
func display() (x int) {
x = 10
defer func() {
fmt.Println(x)
}()
x = 5
// Deferred functions are executed.
return
}
Result:
5
The variables passed to the anonymous functions from the enclosing function are passed by reference. The deferred function when it is being executed, takes the values held in that memory location at the time of execution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With