The Named Return Value Gotcha with defer in Go

Named return values are initialized at function entry, so modifying them in defer can overwrite intended return values.

Named return values are initialized to zero values at the function start, so defer statements that modify them run after those values are set but before the function returns, potentially overwriting logic intended to change the return.

func divide(a, b int) (result int, err error) {
    defer func() {
        if err != nil {
            result = 0 // Overwrites result if err was set later
        }
    }()
    if b == 0 {
        err = errors.New("divide by zero")
        return // Returns result=0, err=error
    }
    result = a / b
    return
}

To fix this, avoid modifying named returns inside defer or use a local variable for the return value and assign it at the end.