Ad space (banner)
๐ŸนGo Lessons
Lesson 50 / 68

Cleanup Logic with defer

In this lesson you will learn to write cleanup logic with defer in Go, so certain work always runs when a function ends. This is for anyone searching for "Go defer how to use".

Go has no finally block, but defer lets you book work to be run without fail when the function ends. It is the usual choice for closing files or writing a completion log.

The sample code declares defer fmt.Println("Ending the calculation") at the top of divide(), so that message always appears last whether the function finishes normally or returns early.

A common stumbling block for beginners is the order in which several defers run. Note that they run in reverse order of declaration - last in, first out.

In real-world development defer is common wherever an external resource such as a file or a database connection must be closed reliably after being opened.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)