有没有大佬解释下 Golang 的匿名函数的 defer 问题

2019-11-18 14:50:08 +08:00
 passMeBy

package main

import "fmt"

func a()(i int) {

defer func(){

fmt.Println("2:",i)

}()

defer fmt.Println("1:",i)

i++

return 

}

func main() {

a()

}

output:

1: 0

2: 1

匿名函数的 defer 为何是 1,是因为闭包函数共享了作用域的变量?

1482 次点击
所在节点    程序员
5 条回复
codehz
2019-11-18 15:03:05 +08:00
defer 时,(顶层)函数参数是立即求值的,然后匿名函数的话,自然就是用外面的 i 了
(这种技巧也可以用来统计函数运行时间 defer Count(time.Now())
ManjusakaL
2019-11-18 15:04:29 +08:00
https://golang.org/ref/spec#Defer_statements 其实看下 spec 就明白了

> Each time a "defer" statement executes, the function value and parameters to the call are evaluated as usual and saved anew but the actual function is not invoked
BOYPT
2019-11-18 15:27:59 +08:00
挺有意义的,比如 defer cancel()后面又有另外一个 xx, cancel := xxx,前面的 cancel 不会被覆盖
TypeErrorNone
2019-11-18 17:33:44 +08:00
首先 i = 0
执行 defer fmt.Println("1:",i),这里是传参操作,把 i=0 传值进去了。
执行 defer func(){fmt.Println("2:",i)}时,i=1,所以输出 1
TypeErrorNone
2019-11-18 17:35:33 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/620669

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX