结果:
4 5 6
1 2 3
问:我开始的理解是函数执行到非defer语句的最后一行才去执行defer语句,那么当函数执行完后a,b,c的值应该已经被更新到4,5,6了,那么此时再执行defer语句时应该传入a,b,c最新的值,也就是两次输出:4,5,6。但从结果看来,我只能猜测是:执行到defer语句时,系统会把当时环境的a,b,c的值压入“栈”中,所以不是等到函数非defer语句执行完才去获取abc最新值当参数传入foo。 那么defer后面的机制到底是怎么去实现的呢? 官方网上不去,有谁能说说它的原理或者有官方的说法链接给发一个呗.
官网blog 有对defer, panic, and recover的详细说法,不知道你能不能打开
https://blog.golang.org/defer...
摘录一下
A defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns. Defer is commonly used to simplify functions that perform various clean-up actions.
The behavior of defer statements is straightforward and predictable. There are three simple rules:
1. A deferred function's arguments are evaluated when the defer statement is evaluated.
In this example, the expression "i" is evaluated when the Println call is deferred. The deferred call will print "0" after the function returns.
2. Deferred function calls are executed in Last In First Out order after the surrounding function returns.
This function prints "3210":
3. Deferred functions may read and assign to the returning function's named return values.
In this example, a deferred function increments the return value i after the surrounding function returns. Thus, this function returns 2:
希望你能理解