The program below returns
<nil>
hello
I expected both to return "hello" but it's not the case. I've found that the behaviour is given as example in the language spec.
For instance, if the deferred function is a function literal and the surrounding function has named result parameters that are in scope within the literal, the deferred function may access and modify the result parameters before they are returned.
My question is: why does defer works differently with variables defined in the surrounding function than with named results? Isn't it just a closure executed before the surrounding function returns?
package main
import (
"errors"
"fmt"
)
func main() {
fmt.Println(up())
fmt.Println(up2())
}
func up() error {
var err error
defer func() {
err = errors.New("hello")
}()
return err
}
func up2() (err error) {
defer func() {
err = errors.New("hello")
}()
return err
}
func up3() error {
var err error
fn := func() {
err = errors.New("hello")
}
fn()
return err
}