defer func(参数){}
defer func(参数){}
- 参考代码
func main(){
fmt.Println("================打印顺序===============")
a:=1
b:=2
defer calc("1",a,calc("10",a,b))
a=0
defer calc("2",a,calc("20",a,b))
b=1
fmt.Println("a=",a,"b=",b)
}
func calc(index string, a,b int)int{
ret := a+b
fmt.Println(index,a,b,ret)
return ret
}
- 输出结果
================打印顺序===============
10 1 2 3
20 0 2 2
a= 0 b= 1
2 0 2 2
1 1 3 4
- 结果分析
- defer运行特点
- 在return之后执行
- 先赋值后放入堆栈
- defer运行特点