Golang in sixty seconds — defer

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:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Richard Bell

Richard Bell

444 Followers

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