gpt4 book ai didi

go - defer 和命名返回值是如何工作的?

转载 作者:IT老高 更新时间:2023-10-28 13:00:35 24 4
gpt4 key购买 nike

我刚开始学习 Go,我对一个关于使用 defer 更改 The Go Blog - Defer, Panic, and Recover 中的命名返回值的示例感到困惑。 .

例子说:

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

但正如我从 A Tour of Go - Named return values 那里学到的一样

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

我在下面的代码和函数 b 中进行了测试,它返回 1,因为它不是上面提到的“A return statement without arguments”的情况。

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

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

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

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

return 1 

等于:

i = 1
return

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

请帮我确认一下,谢谢!

最佳答案

A defer statement pushes a function call onto a list. The list of saved calls is executed after the surrounding function returns. -- The Go Blog: Defer, Panic, and Recover

上述说法的另一种理解方式:

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 后,执行 defer func() { i++ }()。因此,按照执行顺序:

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

为了理解起见:

 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. “第三”

关于go - defer 和命名返回值是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37248898/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com