Defer Statements in Go: A Short Crash Course

blazingbits

BlazingBits

Posted on May 30, 2024

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!

💖 💪 🙅 🚩
blazingbits
BlazingBits

Posted on May 30, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Structs in Go
beginners Structs in Go

July 15, 2019

Functions in Go
beginners Functions in Go

July 5, 2019

Conditionals in Go
beginners Conditionals in Go

June 7, 2019