1、多个defer顺序

image.png

  1. package main
  2. import "fmt"
  3. func main() {
  4. //defer多个,打印顺序是倒的,类似出栈
  5. defer fmt.Println("end1")
  6. defer fmt.Println("end2")
  7. fmt.Println("aaa")
  8. fmt.Println("bbb")
  9. }

image.png

2、defer与return 的执行顺序

  1. package main
  2. import "fmt"
  3. func main() {
  4. deferAndReturn()
  5. }
  6. func deferAndReturn() int {
  7. defer deferFunc()
  8. return returnFunc()
  9. }
  10. func deferFunc() int {
  11. fmt.Println("defer func called...")
  12. return 0
  13. }
  14. func returnFunc() int {
  15. fmt.Println("returnFunc func called...")
  16. return 0
  17. }

结果:return比defer先执行
image.png