defer类似栈,是逆序执行的,
当发生panic时,先执行完前面的所有defer,最后才panic.

示例代码:

package main

import "fmt"

func test(){
	defer func(){
		fmt.Println("defer 1")
	}()
	defer func(){
		fmt.Println("defer 2")
	}()
	defer func(){
		fmt.Println("defer 3")
	}()
	panic("temp")
}
func main(){
	test()
}

运行结果:

PS E:\goproject> go run "e:\goproject\go_test1\main.go"
defer 3
defer 2
defer 1
panic: temp