Defer and closures


I have the following code.
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 (

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 {


The return values must be named in order for them to be modified in a deferred function:

1 Like

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