Golang in sixty seconds — defer

Richard Bell
1 min readAug 9, 2022
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.

More Golang in sixty seconds

Get Unlimited access to Medium

Buy me a coffee if you enjoyed the article :)

--

--

Richard Bell
Richard Bell

Written by Richard Bell

Father to two beautiful baby girls | Husband to a generous wife | Lead Software Engineer | Hobby collector | Support me at ko-fi.com/richardtbell

No responses yet