DEV Community

BlazingBits
BlazingBits

Posted on

Defer Statements in Go: A Short Crash Course

#go

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 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!

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay