Defer and closures

Hi

I have the following code.

https://play.golang.org/p/IkqKQEp27_1
I would have expected it to return a non nil error. In the defer I am setting the error to non nil. But what is returning is a nil. Cant reason it out as to why it is nil. Appreciate some insights. I have for sure read the spec wrong

import (
“fmt”
“log”
)

func cleanUp() error {
return fmt.Errorf("**ERROR: cleanUp() error")
}

func getMessageBug()(string, error) {
var err error
s := “Ok”

fmt.Println(&err, err)
defer func() {
	err = cleanUp()
	s = "This too is buggy"
	fmt.Println(&err, err)
}()

return s, err

}

func main() {

msg, err:= getMessageBug()
if err != nil {
	log.Println(err)
}
log.Println(msg)

}

The return values must be named in order for them to be modified in a deferred function: https://play.golang.org/p/MdnuGzMM-UD

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.