英文:
Does defer runs after function returns?
问题
我一直盯着这段代码看,但无法理解它的行为原因。
package main
import (
"fmt"
)
var i int
func example() int {
defer func() {
fmt.Println("defer")
i = 1
}()
fmt.Println("first")
return i
}
func main() {
fmt.Println(example())
fmt.Println(i)
}
起初,我期望的输出是:
first
defer
1
1
但是,正如你在playground中看到的,实际输出是:
first
defer
0
1
这是一个延迟执行的匿名函数的行为吗?不是的。
那么,为什么会打印出0呢?
英文:
I've been staring at this code and can't figure out the why of its behavior.
package main
import (
"fmt"
)
var i int
func example() int {
defer func() {
fmt.Println("defer")
i = 1
}()
fmt.Println("first")
return i
}
func main() {
fmt.Println(example())
fmt.Println(i)
}
At first, the expected output for me is:
first
defer
1
1
But, as you can see in the playground the actual output is:
first
defer
0
1
Is it a deferred anonymous function behavior? Nope
So, why is it printing 0?
答案1
得分: 7
defer在函数返回后执行吗?
是的。
那为什么会打印0呢?
因为你返回了0。
example() 函数通过值返回一个 int。当评估 return i 时,会返回 i 的当前值。在该返回语句评估完之后,defer 函数执行,将 i 存储的值更改为 1。但是 0 的值已经是返回值了。
Go 语言允许修改函数的返回值,但前提是返回值有一个名称。
例如,下面的代码会返回 1:
func example() (j int) {
defer func() { j = 1 }()
return 0
}
但在你的情况下,你没有给返回变量命名,所以无法在 defer 中修改它。
英文:
> Does defer runs after function returns?
> So, why is it printing 0?
Because you're returning 0.
example() returns an int by value. when return i is evaluated, is current value is returned. After that return is evaluated, the defer function executes, changing the value stored at i to 1. But the 0 value is already the return value.
Go makes it possible to modify the return value of a function, but only if the return value has a name.
func example() (j int) {
defer func() { j = 1 }()
return 0
}
But in your case, you're not naming your return variable, so you can't modify it in a defer.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论