package main
func main() {
println(func1())
println(func2())
println(func3())
}
func func1() (t int) {
defer func() {
t = 3
}()
return t
}
func func2() int {
t := 0
defer func() {
t = 3
}()
return t
}
func func3() (t int) {
defer func() {
t = 3
}()
return 2
}
输出:
3
0
3
可见defer可以在函数返回前修改命名返回值,非命名返回值则不能修改。换句话说,命名返回值是defer修改函数返回值的唯一途径。
“If the deferred function is a function literal and the surrounding function has named result parameters that are in scope within the literal, the deferred function may access and modify the result parameters before they are returned”
另外需要注意的是:在有命名返回值的函数func3里return 2 等价于t = 2 然后 return。例如下列返回值是1
func b() (i int) { // return 1
i = 2
return 1
}