I write the follow code
package main
import "fmt"
func main() {
defer func() func() {
fmt.Println("start")
return func() {
fmt.Println("end")
}
}()()
fmt.Println("aaaa")
return
}
and I except output is aaaa start end
but actual output is start aaaa end
I can't understand why output "start" before "aaaa"
The specification says:
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.
The deferred function call is the last ()
in the defer statement. The expression returning the function value is evaluated at the time of the defer statement.
Since defer statement needs to evaluate the statement, in your code, the func() (the func() right after "defer" keyword) returns a function type, defer statement needs to actually execute the func() to get the return function. So your code prints out "start" first.
If your function does not return a function type, then the function body will not be executed until enclosing function returns.