为什么在此延迟语句(无返回)运行时不返回返回值?
I am reading through the go specification and don't fully understand the behavior of an example for defer.
// f returns 1
func f() (result int) {
defer func() {
result++
}()
return 0
}
The function has a named return, which an anonymous deferred function increments. The function ends with "return 0". This value is not returned, but the incremented variable instead.
In trying to understand this behavior, I've run into more questions. If I assign a value to the return variable, that seems to have no effect on the return value.
//b returns 1
func b() (result int) {
result = 10
defer func() {
result++
}()
return 0
}
However, if the last line is changed to:
return result
Things behave as I would expect.
https://play.golang.org/p/732GZ-cHPqU
Can someone help me better understand why these values get returned and the scope of these functions.
我正在阅读执行规范,并且没有完全理解示例的延迟行为。 p>
// f返回1
func f( )(结果int){
延迟func(){
结果++
}()
返回0
}
code> pre>
该函数具有一个命名的 返回值,匿名延迟函数会递增。 该函数以“返回0”结束。 不返回此值,而是返回递增的变量。 p>
在试图理解此行为时,我遇到了更多问题。 如果我为返回变量赋值,那么这似乎对返回值没有影响。 p>
// b返回1
func b()(result int){
结果= 10
延迟func(){
结果++
}()
返回0
}
code> pre>
但是,如果最后一行 更改为: p>
返回结果
code> pre>
事物的行为符合我的预期。 p>
https://play.golang.org/p/732GZ-cHPqU a> p>
有人可以帮助我更好地理解为什么返回这些值以及这些函数的范围。 p>
div>
The specification says this about deferred functions:
if the deferred function is a function literal and the surrounding function has named result parameters that are in scope within the literal, the deferred function may access and modify the result parameters before they are returned.
and and this about return statements:
A "return" statement that specifies results sets the result parameters before any deferred functions are executed.
Example 1:
func f() (result int) {
defer func() {
result++
}()
return 0
}
The result
variable is initialized to zero; the return statement sets result
to zero; the deferred function increments result
to 1; the function returns 1.
Example 2:
func b() (result int) {
result = 10
defer func() {
result++
}()
return 0
}
The result
variable is set to 10 in the first statement of the function; the return statement sets result
to zero; the deferred function increments result
to 1; the function returns 1.
Example 3:
func c() (result int) {
result = 10
defer func() {
result++
}()
return result
}
The result
variable is set to 10 in the first statement of the function; the return statement sets result
to 10; the deferred function increments result
to 11, the function returns 11.