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
", x)
x = 7
return 9
}
func test2() (x int) {
defer func() {
fmt.Printf("in defer: x = %d
", x)
}()
x = 7
return 9
}
func test3() (x int) {
x = 7
defer fmt.Printf("in defer: x = %d
", x)
return 9
}
func main() {
fmt.Println("test1")
fmt.Printf("in main: x = %d
", test1())
fmt.Println("test2")
fmt.Printf("in main: x = %d
", test2())
fmt.Println("test3")
fmt.Printf("in main: x = %d
", 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.