Go tip: how to set a return value in a deferred function

,

Learned something new today from the Applied Go Newsletter – you can set a return value in a deferred function used named parameters:

package main

import "fmt"

func outerFunction() (err error) {
	defer func() {
		// do some cleanup
		if true /* cleanup has failed */ {
			err = fmt.Errorf("cleanup failed")
		}
	}()
	return err
}
func main() {
	fmt.Println(outerFunction())
}

Without a named parameter, there is no way for a deferred function to access the return values.