[Go]Deferred函数案例
1 min read
package main
func main() {
println(DeferFunc1(1))
println(DeferFunc2(1))
println(DeferFunc3(1))
}
func DeferFunc1(i int) (t int) {
t = i
defer func() {
t += 3
}()
return t
}
func DeferFunc2(i int) int {
t := i
defer func() {
t += 3
}()
return t
}
func DeferFunc3(i int) (t int) {
defer func() {
t += i
}()
return 2
}
运行结果:
4
1
3
解析:
首先,只有在函数执行完毕后,这些被延迟的函数才会执行;其次,defer语句中的函数会在return语句更新返回值变量后再执行,而且函数中定义的匿名函数可以访问该函数包括返回值变量在内的所有变量。所以,DeferFunc1, DeferFunc3,分别返回4,3。DeferFunc2中因为defer中的匿名函数更新的是函数中变量t,不会影响返回值所以返回1。
Last updated on 2018-03-11