Today I Learned: Deferring Functions in Golang

Thursday June 18, 2020 at 07:21 pm CDT

Golang allows you to specify a function to call after the calling function returns. Let’s say you have the following lines of code:

func greeting() {
  defer fmt.Println("I'm swell! Thanks for asking!")

  fmt.Println("How are you?")
}

greeting()

The output after calling the greeting function is

How are you?
I'm swell! Thanks for asking!

defer is useful for things like cleanup and logging. For instance, if you need to close an open file, defer is a great way to ensure that the file is closed once the function returns.

func writeToFile() {
  defer closeFile()
  ...
}

Note that the arguments to the function following defer are evaluated immediately. Hence, the following will return an error

func willNotWork(){
  defer fmt.Println(msg)
  msg := "ohai"
}

Photo by Alexandru Goman on Unsplash