本文主要研究一下golang的defer
对于命名返回值
),然后执行defer,最后函数返回// f returns 42 func f() (result int) { defer func() { // result is accessed after it was set to 6 by the return statement result *= 7 }() return 6 }
这里return先给result赋值为6,之后执行defer,result变为42,最后返回42
func f() int { result := 6 defer func() { // result is accessed after it was set to 6 by the return statement result *= 7 }() return result }
这里return确定返回值6,之后defer修改result,最后函数返回return确定的返回值
func multiDefer() { for i := 3; i > 0; i-- { defer func(n int) { fmt.Print(n, " ") }(i) } for i := 3; i > 0; i-- { defer fmt.Print(i, " ") } }
多个defer函数,按顺序逆序执行,这里输出1 2 3
var fc func() string func main() { fmt.Println("hello") defer fc() }
由于defer指定的func为nil,这里panic
func main() { for i := 3; i > 0; i-- { defer func() { fmt.Print(i, " ") }() } }
由于defer这里调用的func没有参数,等执行的时候,i已经为0,因而这里输出3个0
defer可以拆解为return赋值,defer执行,最后代码返回三步;defer的顺序按逆序执行。