defer - modify named return value vs non-named return value

465 views Asked by At

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?

0

There are 0 answers