Golang in sixty seconds — defer

Wall with several clocks on it
Photo by Karim MANJRA on Unsplash

Golang has a special statement called defer which causes the function to be run after the function completes. Let's look at an example:

func one() {
  fmt.Println("1")
}
func two() {
  fmt.Println("2")
}
func main() {
  defer two()
  one()
}

Calling the main function we would see the following output:

1
2

It would be the same as calling the functions in this order:

func main() {
  one()
  two()
}

Seems a little pointless in this example, however it is very useful for clean up tasks as it will run even if an error occurs, or something is returned. You may see something like this:

db = CreateDBConnection()
defer db.CloseConnection()

Followed by some useful operations on the database. Another advantage here is that it keeps our close call close to the create call so it's easier to see that it's being handled.

Richard Bell

Self taught software developer with 12 years experience excelling at JavaScript/Typescript, React, Node and AWS.

I love learning and teaching and have mentored several junior developers over my career. I find teaching is one of the best ways to solidify your own learning, so in the past few years I've been maintaining a technical blog where I write about some things that I've been learning.

I'm passionate about building a teams culture and processes to make it efficient and satisfying to work in. In many roles I have improved the quality and reliability of the code base by introducing or improving the continuous integration pipeline to include quality gates.