我推迟了一个函数的返回函数,命令是什么 [英] I defer a function return function, what is the order

查看:51
本文介绍了我推迟了一个函数的返回函数,命令是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写以下代码

package main

import "fmt"

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

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

}

除了输出是aaaa start end

and I except output is aaaa start end

但实际输出是从开始到结束

but actual output is start aaaa end

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

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

推荐答案

规范说:

每次执行"defer"语句时,都会照常评估调用的函数值和参数并重新保存,但不会调用实际函数.

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.

延迟函数调用是defer语句中的最后一个().返回函数值的表达式在defer语句时进行求值.

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.

这篇关于我推迟了一个函数的返回函数,命令是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆