Code
func deferModifyReturnValue() int {
x := 0
defer func() {
x += 1 // executed before return,
}()
return x
}
func deferModifyNamedReturnValue() (x int) {
defer func() {
x += 1 // executed before return,
}()
return
}
func TestDeferModifyReturnValue(t *testing.T) {
assert.Equal(t, 0, deferModifyReturnValue())
assert.Equal(t, 1, deferModifyNamedReturnValue())
}
Question
The test passes.
I can understand why the deferModifyNamedReturnValue() return 1, because defer modify it right before return.
But, how the deferModifyReturnValue() return 0? Does it make a copy to stack before the modification?
named return valuecase, since the return value is already defined & set, thus the defer take effect. Right ?xafter thereturnstatement: the variable has nothing to do with the value being returned. Ifxitself is the result parameter, its value will be used when the function ends. If a deferred function modifies it after areturn, the new value will be returned.returnstatement is executed. Deferred functions run after this. In the first example thexvariable is not the result parameter, so again, changing it has no effect on the value being returned.