What's the order of defer and named return value

Viewed 101

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 Answers

The order of execution is:

  1. The return statement sets result parameters.
  2. Deferred calls execute.
  3. 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.

Related