请输出结果
func calc(index string, a, b int) int{
ret := a + bfmt.Println(index, a, b, ret)return ret
}
func main(){
a,b:=1,2defer calc("1", a, calc("10", a, b))a = 0defer calc("2", a, calc("20", a, b))b = 1
}
答案:
10 1 2 3
20 0 2 2
2 0 2 2
1 1 3 4
执行分析
0.a,b:=1,2
1.defer calc(“1”, 1, calc(“10”, 1, 2))
2.calc(“10”, 1, 2) //=> 10 1 2 3
3.defer calc(“1”, 1, 3)
4.a=0
5.defer calc(“2”, 0, calc(“20”, 0, 2))
6.calc(“20”, 0, 2) //=> 20 0 2 2
7.defer calc(“2”, 0, 2)
8.calc(“2”, 0, 2) //=> 2 0 2 2
9.calc(“1”, 1, 3) //=> 1 1 3 4
总结:
defer 参数携带运算先运算
defer间执行顺序:后来居上