2

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?

5
  • 4
    From the documentation: "deferred functions are executed after any result parameters are set by that return statement" Commented Jan 18, 2022 at 17:59
  • @JimB Ok, so you mean: A) in the non-named case, a copy to stack is made before the defer function is executed, thus return value is not effected by defer; B) and in the named return value case, since the return value is already defined & set, thus the defer take effect. Right ? Commented Jan 18, 2022 at 18:11
  • When the result parameter is not named, creating a local variable has no connection to the return value. It doesn't matter if a deferred function changes the value of x after the return statement: the variable has nothing to do with the value being returned. If x itself is the result parameter, its value will be used when the function ends. If a deferred function modifies it after a return, the new value will be returned. Commented Jan 18, 2022 at 18:13
  • @icza your comment doesn't actually answer my doubt clearly, and the linked question in duplication is not identical to my question neither. Commented Jan 18, 2022 at 18:16
  • 9
    Whether the result of the return's expression is stored on the stack is irrelevant (can be implementation specific). What matters is that the expression is evaluated when the return statement is executed. Deferred functions run after this. In the first example the x variable is not the result parameter, so again, changing it has no effect on the value being returned. Commented Jan 18, 2022 at 18:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.