Go defer的实现机制到底怎么回事???

新手上路,请多包涵

clipboard.png

结果:
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后面的机制到底是怎么去实现的呢? 官方网上不去,有谁能说说它的原理或者有官方的说法链接给发一个呗.

阅读 3.8k
2 个回答

官网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.

func a() {
    i := 0
    defer fmt.Println(i)
    i++
    return
}

2. Deferred function calls are executed in Last In First Out order after the surrounding function returns.

This function prints "3210":

func b() {
    for i := 0; i < 4; i++ {
        defer fmt.Print(i)
    }
}

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:

func c() (i int) {
    defer func() { i++ }()
    return 1
}

希望你能理解

新手上路,请多包涵

太感谢@勤奋的小小尘,完全解决了心中的疑虑,果然如此。我这的VPN用不了了,某度又找不准想要的。真是千恩万谢

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题