DEV Community

BlazingBits
BlazingBits

Posted on

3

Defer Statements in Go: A Short Crash Course

What is the defer statement?

In Go, a defer statement gives you the ability to execute a function AFTER its containing function has finished execution.

The easiest way to think about it is a callback, or a finally block for developers more familiar with Java.

You will commonly see defer statements being used to clean up resources, such as files and database connections.

defer Statement Syntax

func main() {
  myFile, err := os.Open("my-file.txt")
  defer myFile.close()

  if err != nil {
    panic(err)
  }
}

Enter fullscreen mode Exit fullscreen mode

The above is an example of using defer to clean up resources, in this case, closing a file after we are done with it. The defer statement will not execute until after our main method has finished its execution.

Using defer directly after opening a resource that needs to be manually closed or handled (like files!) is a best practice. This way you know for sure there will be no left over resources and you won't forget to manually close it later on in the code.

I like to keep such defer statements as close as possible, ideally right under, the line that opens the resources.

Using Multiple defer Statements

defer statements are placed on a stack. Meaning the last defined statement will be the first to be executed. This is something I had to learn the hard way after facing a particularly confusing bug!

Consider the following code:

import "fmt"

func main() {
    defer deferredPrint("0")
    defer deferredPrint("1")
    defer deferredPrint("2")
}

func deferredPrint(s string) {
    fmt.Printf("%s\n", s)
}
Enter fullscreen mode Exit fullscreen mode

What might its output be?

Since defer statements are placed in a call stack (LIFO) the output is the following:

2
1
0
Enter fullscreen mode Exit fullscreen mode

Notice that the last defined defer statement is executed first!

Image of Wix Studio

2025: Your year to build apps that sell

Dive into hands-on resources and actionable strategies designed to help you build and sell apps on the Wix App Market.

Get started

Top comments (0)

Eliminate Context Switching and Maximize Productivity

Pieces.app

Pieces Copilot is your personalized workflow assistant, working alongside your favorite apps. Ask questions about entire repositories, generate contextualized code, save and reuse useful snippets, and streamline your development process.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay