英文:
What's the order of defer and named return value
问题
看一下这两个代码块:
// 返回 0
func f() int {
	res := 0 
	defer func(){
		res++
	}()
	return res
}
我知道 defer 表达式在 return 表达式之后执行。
但是为什么有命名返回值时会有所不同呢?
为什么下面的函数不返回 0?
// 返回 1
func f() (res int) {
	res = 0 
	defer func(){
		res++
	}()
	return res
}
英文:
Look at these two blocks of code:
// return 0
func f() int {
	res := 0 
	defer func(){
		res++
	}()
	return res
}
I know that the defer expression is executed after the return expression.
But why is it different when there's a named return value?
Why doesn't the following function return a 0?
// return 1
func f() (res int) {
	res = 0 
	defer func(){
		res++
	}()
	return res
}
答案1
得分: 5
执行顺序如下:
- return语句设置结果参数。
 - 延迟调用执行。
 - 函数返回结果参数。
 
延迟函数可以在函数返回之前修改命名的结果参数。
第一个示例中的延迟函数修改了局部变量res,而不是无名结果参数。函数f返回0,因为return将结果参数设置为0,而延迟函数不会改变结果参数。
第二个函数返回1,因为延迟函数修改了结果参数res。
英文:
The order of execution is:
- The return statement sets result parameters.
 - Deferred calls execute.
 - The function returns the result parameters.
 
A deferred function can modify named result parameters before the function returns.
The deferred function in the first example modifies the local variable res, not the unnamed result parameter. The function f returns 0 because return sets the result parameter to 0 and the deferred function does not change the result parameter.
The second function returns 1 because the deferred function modifies the result parameter res.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论