Golang in sixty seconds — defer
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.
Get Unlimited access to Medium
Buy me a coffee if you enjoyed the article :)