Will the print in the defer function of the following code be executed?
package main
import (
"errors"
"fmt"
)
func Foo(n int64) (err error) {
defer func() {
if err != nil {
fmt.Println("error in defer is :", err)
}
}()
if n <= 0 {
return errors.New("n <= 0")
}
return nil
}
func main() {
Foo(-1)
}
You can use GoLand's DEBUG function to set several breakpoints as shown in the figure to track the order of program execution
Through debugging, you can see that the code execution sequence is code block 2 —> 3 —> 4 —> 5 (where marked as 1
is just a declaration of a defer function, and it did not start execution)
After the second step is executed, the function return value err will be automatically assigned, so when the fourth step is executed, err is not nil, so the print in defer will be executed.
Through the above example, we can also think carefully about the sentence "defer function is executed before return".
The return mentioned is only the return keyword, and does not include other logic that follows the return.