defer :
1 函数离开前执行
2 FILO 栈
package main import "fmt" func trace(s string) { fmt.Println("entering:", s); } func untrace(s string) { fmt.Println("leaving:", s); } func a() { trace("a"); defer untrace("a"); fmt.Println("in a") } func b() { trace("b"); defer untrace("b"); fmt.Println("in b"); a() } func trace2(s string) string { fmt.Println("entering:",s) return s } func un(s string) { fmt.Println("leaving:",s) } func a2() { defer un(trace2("a")) fmt.Println("in a") } func b2() { defer un(trace2("b")) fmt.Println("in b") a2() } func main() { for i:=0;i<5;i++{ defer fmt.Println(i) } b2(); }
有疑问加站长微信联系(非本文作者)