# defer 的一些用法和猜测

``````func fooA() float64 {
defer func() {
if err := recover(); err != nil {
}
}()

*(*float64)(nil) = 0.1 // panic
return 1.0
}``````

`fooA()` 返回0。

``````func fooB() float64 {
defer func() float64 {
if err := recover(); err != nil {
return 1.1
} else {
return 1.2
}
}()

*(*float64)(nil) = 0.1
return 1.0
}``````

`fooB()` 返回0。

``````func fooC() (x float64) {
defer func() {
if err := recover(); err != nil {
x = 1.1
return
}
}()

*(*float64)(nil) = 0.1
return 1.0
}``````

`fooC()`返回1.1。

That is, if the surrounding function returns through an explicit return statement, deferred functions are executed after any result parameters are set by that return statement but before the function returns to its caller.

DeferFunc1 和 DeferFunc3 还比较好解释，对于文中的DeferFunc2，强行猜测了一下：

``````func dfB(i int) int { // return anonymous int，we assume it named `noNameI`。
t := i // Local var t is assigned to 1.
defer func() {
// Here noNameI is 2, t is 1.
t += i // t is 3, noNameI unchanged.
}()
return 2 // noNameI is assigned to 2.
}``````

`dfB()` 返回 2，为什么呢？