我推迟一个函数返回函数,顺序是什么?

huangapple go评论142阅读模式
英文:

I defer a function return function, what is the order

问题

我写了以下代码:

package main

import "fmt"

func main() {
    defer func() func() {
        fmt.Println("start")
        return func() {
            fmt.Println("end")
        }
    }()()
    fmt.Println("aaaa")
    return
}

我期望的输出是 "aaaa start end",但实际输出是 "start aaaa end"。

我不明白为什么会在 "aaaa" 之前输出 "start"。

英文:

I write the follow code

package main

import "fmt"

func main() {
    defer func() func() {
        fmt.Println("start")
        return func() {
            fmt.Println("end")
        }

    }()()
    fmt.Println("aaaa")
    return

}

and I except output is aaaa start end

but actual output is start aaaa end

I can't understand why output "start" before "aaaa"

答案1

得分: 1

根据规范所述:

> 每次执行“defer”语句时,函数值和调用的参数会像平常一样被评估并重新保存,但实际的函数不会被调用。

延迟函数调用是defer语句中的最后一个()。返回函数值的表达式在defer语句执行时被评估。

英文:

The specification says:

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

The deferred function call is the last () in the defer statement. The expression returning the function value is evaluated at the time of the defer statement.

答案2

得分: 0

由于defer语句需要评估语句,在你的代码中,func()(即在"defer"关键字之后的func())返回一个函数类型,defer语句需要实际执行func()以获取返回的函数。因此,你的代码首先打印出"start"。

如果你的函数不返回一个函数类型,那么函数体将不会执行,直到封闭函数返回。

英文:

Since defer statement needs to evaluate the statement, in your code, the func() (the func() right after "defer" keyword) returns a function type, defer statement needs to actually execute the func() to get the return function. So your code prints out "start" first.

If your function does not return a function type, then the function body will not be executed until enclosing function returns.

huangapple
  • 本文由 发表于 2017年9月2日 00:33:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/46004535.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定