延期和命名返回值如何工作? [英] How does defer and named return value work?

查看:74
本文介绍了延期和命名返回值如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习Go,我对一个使用更改 Go博客-推迟,恐慌和恢复.

I just started learning Go and I got confused with one example about using defer to change named return value in the The Go Blog - Defer, Panic, and Recover.

该示例说:

  1. 延迟的函数可以读取并分配给返回函数的命名返回值.

在此示例中,延迟函数在周围函数返回后递增返回值i.因此,该函数返回2 :

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
}

但是,正如我从旅行之路-命名返回值中学到的东西

不带参数的return语句返回命名的返回值.这被称为裸露".返回.

A return statement without arguments returns the named return values. This is known as a "naked" return.

我在以下代码中进行了测试,并在函数b中返回了1,因为它不是"不带参数的return语句".上面提到的情况.

I tested in the following code and in function b it returns 1 because it wasn't the "A return statement without arguments" case mentioned above.

func a() (i int) { // return 2
    i = 2
    return
}

func b() (i int) {  // return 1 
    i = 2
    return 1
}

所以我的问题是在第一个示例中,周围的函数c有一个命名的返回值i,但函数c使用的是return 1,在第二个示例中,我们可以看到它无论返回什么值都应该有return 1 i是.但是为什么在i的延迟函数中更改后,c函数返回值i而不是值1?

So my question is in the first example, the surrounding function c has a named return value i, but the function c uses return 1 which in the second example we can see it should have return 1 no matter what value i is. But why after i changes in the deferred function the c function returns the value of i instead the value 1?

当我输入问题时,我可能已经猜到了答案.是因为:

As I was typing my question, I might have guessed the answer. Is it because:

return 1 

等于:

i = 1
return 

在具有命名返回值变量i的函数中?

in a function with a named return value variable i?

请帮助我确认,谢谢!

推荐答案

defer语句将函数调用推送到列表上.周围函数返回后,将执行保存的呼叫列表. - The Go博客:推迟,紧急和恢复

了解上述说法的另一种方法:

Another way to understand the above statement:

一个延迟语句推动一个函数调用到堆栈上.在周围的函数返回之前,将立即调用已保存的弹出(LIFO)和延迟函数的堆栈.

A defer statements pushes a function call onto a stack. The stack of saved calls popped out (LIFO) and deferred functions are invoked immediately before the surrounding function returns.

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

返回1后,将执行延迟func() { i++ }().因此,按执行顺序:

After 1 is returned, the defer func() { i++ }() gets executed. Hence, in order of executions:

  1. i = 1(返回1)
  2. i ++(延迟功能从堆栈中弹出并执行)
  3. i == 2(命名变量i的最终结果)


为便于理解:


For understanding sake:

 func c() (i int) {
    defer func() { fmt.Println("third") }()
    defer func() { fmt.Println("second") }()
    defer func() { fmt.Println("first") }()

    return 1
}

执行顺序:

  1. i = 1(返回1)
  2. 第一"
  3. 秒"
  4. 第三"

这篇关于延期和命名返回值如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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