0
0
GoConceptBeginner · 3 min read

What is Defer Order in Go: Explanation and Example

In Go, deferred functions are executed in last-in-first-out (LIFO) order when the surrounding function returns. This means the last defer statement added will run first, and the first added will run last.
⚙️

How It Works

Imagine you are stacking plates one on top of another. When you want to use a plate, you take the top one first. In Go, defer statements work like this stack of plates. Each defer adds a function to a stack, and when the surrounding function finishes, Go runs these deferred functions starting from the last one added to the first.

This last-in-first-out order ensures that cleanup or final steps happen in the reverse order of setup. For example, if you open multiple resources, you can defer closing them in the order you opened them, and Go will close the last opened resource first, which is often the correct order.

💻

Example

This example shows three deferred print statements. They will print in reverse order when the function ends.
go
package main

import "fmt"

func main() {
    defer fmt.Println("First defer")
    defer fmt.Println("Second defer")
    defer fmt.Println("Third defer")
    fmt.Println("Function body")
}
Output
Function body Third defer Second defer First defer
🎯

When to Use

Use defer to ensure important cleanup tasks happen no matter how a function exits, such as closing files, unlocking mutexes, or releasing resources. The LIFO order is helpful when you have multiple resources to clean up in reverse order of acquisition.

For example, if you open two files, you can defer closing each right after opening it. When the function ends, Go will close the second file first, then the first file, preventing resource leaks and ensuring proper cleanup.

Key Points

  • Deferred functions run after the surrounding function returns.
  • They execute in last-in-first-out (LIFO) order.
  • This order helps manage resources by cleaning up in reverse order of setup.
  • Defer is useful for cleanup tasks like closing files or unlocking.

Key Takeaways

Deferred functions in Go run in last-in-first-out order when the function returns.
Use defer to guarantee cleanup actions happen even if the function exits early.
Defer order helps manage multiple resources by cleaning up in reverse order.
Each defer adds a function to a stack that runs after the surrounding function finishes.