DEV Community

Cover image for Using defer in Go: Best Practices and Common Use Cases
zakaria chahboun
zakaria chahboun

Posted on

Using defer in Go: Best Practices and Common Use Cases

In Go, the defer keyword is a powerful tool that helps manage resources and ensure that cleanup actions are performed when a function exits. The deferred functions are executed when the surrounding function returns, whether it returns normally, due to an error, or because of a panic. This ensures that cleanup code runs regardless of how the function exits, making resource management simpler and more reliable.

Key Points about defer:

  • Execution Timing: Deferred functions are executed in LIFO (Last In, First Out) order when the surrounding function returns, either by completing its execution, encountering a return statement, or due to a panic.
  • Resource Management: It helps in automatically closing resources like files and network connections, unlocking mutexes, and performing other cleanup tasks.

Table of Contents

1. Order of Multiple Defer Statements

In Go, multiple defer statements within a function are executed in reverse order of their appearance. This is useful for managing multiple cleanup tasks, ensuring they are performed in a specific order when the function exits.

stack of books

func exampleFunction() {
    fmt.Println("Start of function")

    defer fmt.Println("First defer: executed last")
    defer fmt.Println("Second defer: executed second")
    defer fmt.Println("Third defer: executed first")

    fmt.Println("End of function")
}
Enter fullscreen mode Exit fullscreen mode

Output:

Start of function
End of function
Third defer: executed first
Second defer: executed second
First defer: executed last
Enter fullscreen mode Exit fullscreen mode

2. Resource Cleanup

One of the most common uses of defer is to ensure that resources like files are properly closed after they are no longer needed.

func processFile(fileName string) error {
    file, err := os.Open(fileName)
    if err != nil {
        return err // Return the error if opening the file fails
    }
    defer file.Close() // Ensure the file is closed when the function exits

    // Process the file...
    return nil
}
Enter fullscreen mode Exit fullscreen mode

os.File implements io.ReadCloser, so using defer here ensures that the file is closed properly, preventing resource leaks.

3. Unlocking Mutexes

When working with concurrency, it’s crucial to release locks to prevent deadlocks. defer helps manage mutexes effectively.

var mu sync.Mutex

func criticalSection() {
    mu.Lock()
    defer mu.Unlock() // Ensure the mutex is unlocked when the function exits

    // Critical section...
}
Enter fullscreen mode Exit fullscreen mode

By deferring mu.Unlock(), you ensure that the mutex is always released, making the code easier to understand and less error-prone.

4. Releasing Database Connections

Database connections should be closed when they are no longer needed to free up resources.

func queryDatabase() error {
    db, err := sql.Open("driver", "database=example")
    if err != nil {
        return err
    }
    defer db.Close() // Ensure the database connection is closed when the function exits

    // Query the database...
    return nil
}
Enter fullscreen mode Exit fullscreen mode

5. Restoring State

  • Example: Changing and Restoring Working Directory

When changing the working directory, it’s important to restore it to its original state.

func changeDirectory() error {
    oldDir, err := os.Getwd()
    if err != nil {
        return err
    }
    err = os.Chdir("/tmp")
    if err != nil {
        return err
    }
    defer os.Chdir(oldDir) // Restore the working directory when the function exits

    // Work in /tmp...
    return nil
}
Enter fullscreen mode Exit fullscreen mode

Using defer makes it easy to restore the original directory automatically.

6. Handling Panics

  • Example: Recovering from Panics

defer can be used to recover from panics and handle errors gracefully.

func safeFunction() {
    defer func() {
        if r := recover(); r != nil {
            log.Println("Recovered from panic:", r)
        }
    }()
    // Code that might panic...
}
Enter fullscreen mode Exit fullscreen mode

By deferring a function that handles panics, you can ensure that your application remains robust even in the face of unexpected errors.

7. Logging and Timing

  • Example: Timing Function Execution

defer is useful for measuring execution time or logging when a function exits.

func measureTime() {
    start := time.Now()
    defer func() {
        duration := time.Since(start)
        log.Printf("Execution time: %v", duration)
    }()

    // Code to measure...
}
Enter fullscreen mode Exit fullscreen mode

This approach simplifies timing code and ensures that the duration is logged when the function completes.

8. Flushing Buffers

  • Example: Flushing Buffered I/O

Buffered I/O operations should be flushed to ensure that all data is written out.

func bufferedWrite() {
    buf := bufio.NewWriter(os.Stdout)
    defer buf.Flush() // Ensure the buffer is flushed when the function exits

    buf.WriteString("Hello, World!")
}
Enter fullscreen mode Exit fullscreen mode

Using defer here guarantees that any buffered data is written out before the function completes.

9. Handling HTTP Request Bodies

  • Example: Closing HTTP Request Body

HTTP request bodies implement io.ReadCloser, so it’s crucial to close them after use to free up resources and avoid leaks.

func handleRequest(req *http.Request) error {
    // Ensure that the request body is closed when the function exits
    defer func() {
        if err := req.Body.Close(); err != nil {
            log.Println("Error closing request body:", err)
        }
    }()

    body, err := io.ReadAll(req.Body)
    if err != nil {
        return err
    }

    // Process the body...
    fmt.Println("Request body:", string(body))

    return nil
}
Enter fullscreen mode Exit fullscreen mode

By deferring the req.Body.Close(), you ensure that the body is closed properly, even if an error occurs while reading or processing it.

10. Risk of Closing a Failed Opening Without defer

When you open a file or other resource in Go, it’s crucial to ensure that the resource is properly closed once it’s no longer needed. However, if you attempt to close a resource after error checking without using defer, you could introduce risks into your code.

  • Example Without defer
file, err := os.Open(fileName)
if err != nil {
    return err // Handle error
}
// Risk: If something goes wrong before this point, the file might never be closed
// Additional operations here...
file.Close() // Attempt to close the file later
Enter fullscreen mode Exit fullscreen mode

Not using defer to close resources in Go can lead to unintended consequences, such as attempting to close a resource that was never successfully opened, resulting in unexpected behavior or panics. Additionally, if an error occurs before the explicit Close() call, the resource might remain open, causing leaks and exhausting system resources. As the code becomes more complex, ensuring all resources are properly closed becomes increasingly difficult, raising the likelihood of overlooking a close operation.

11. Risk of Using defer Before Checking if a File Was Opened

In Go, it's crucial to place a defer statement after verifying that a resource, like a file, was successfully opened.
Placing defer before the error check can introduce several risks and undesirable behavior.

Example of Incorrect Usage

file, err := os.Open(fileName)
defer file.Close() // Incorrect: This should be deferred after the error check
if err != nil {
    return err // Handle error
}
// Additional operations here...
Enter fullscreen mode Exit fullscreen mode

Placing defer file.Close() before checking if os.Open succeeded can cause several issues. If the file wasn't opened and is nil, attempting to close it will lead to a runtime panic since Go executes all deferred functions even when an error occurs. This approach also makes the code misleading, implying that the file was successfully opened when it might not have been, which complicates understanding and maintenance. Furthermore, if a panic does occur, debugging becomes more challenging, especially in complex codebases, as tracing the issue back to the misplaced defer can take additional effort.

12. Conclusion

The defer keyword in Go simplifies resource management and enhances code clarity by ensuring that cleanup actions are performed automatically when a function exits. By using defer in these common scenarios, you can write more robust, maintainable, and error-free code.

Top comments (7)

Collapse
 
bashery profile image
bashery • Edited

so useful

Collapse
 
martinbaun profile image
Martin Baun

What a gem of an article!

Collapse
 
zakariachahboun profile image
zakaria chahboun

you're welcome 🤠

Collapse
 
ang-costa-neto profile image
Angelo Costa

Amazing explanation, thanks for sharing!

Collapse
 
zakariachahboun profile image
zakaria chahboun

You are welcome

Collapse
 
marcello_h profile image
Marcelloh

Not all the defer usages seems correct.

Sometimes you use:

 defer func() {
        if err := req.Body.Close(); err != nil {
            log.Println("Error closing request body:", err)
        }
    }()
Enter fullscreen mode Exit fullscreen mode

and sometimes just:

defer db.Close() // Ensure the database connection is closed when the function exits
Enter fullscreen mode Exit fullscreen mode

You don't know if the database is closed, because you didn't investigate any error that Close() might give you.

So most defers are like the defer func() one.

BTW: Do you know the defer doSomething()()?
Because it is missing in your explanation ;-)

Collapse
 
zakariachahboun profile image
zakaria chahboun

using defer with a function that returns a function is a bit unusual, i didn't know about it!