延迟执行在函数返回后运行吗?

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

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?

Certainly.

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

For example, this returns 1:

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.

huangapple
  • 本文由 发表于 2022年3月19日 20:58:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/71538330.html
匿名

发表评论

匿名网友

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

确定