2 min read

How to Use Defer in Golang: A Comprehensive Guide for Beginners

How to Use Defer in Golang: A Comprehensive Guide for Beginners
Photo by Patrick Hendry / Unsplash

Introduction

In the world of Go programming, managing resources efficiently and handling errors gracefully are critical aspects of writing robust applications. This is where understanding and utilizing the defer keyword becomes vital. Whether you're a beginner in Go or looking to refresh your knowledge, this guide will dive deep into how golang defer and golang recover play a pivotal role in resource management and error handling.

Defining defer statements

To define a defer statement, you use the following syntax:

defer statement

The statement can be any valid Golang statement, such as a function call, a variable assignment, or a return statement.

Executing defer statements

When a defer statement is executed, the statement is not actually executed immediately. Instead, it is added to a list of deferred statements. The deferred statements are then executed in reverse order when the current function returns.

Using defer to perform cleanup tasks

Defer is often used to perform cleanup tasks, such as closing files or releasing resources. For example, the following code opens a file and defers the closing of the file until the end of the function:

func readFile() {
    file, err := os.Open("myfile.txt")
    if err != nil {
        return
    }

    defer file.Close()

    // Read the file
}

In this example, the file.Close() statement is deferred. This means that the file will be closed even if an error occurs in the readFile() function.

Using defer to control the order of execution

Defer can also be used to control the order of execution of statements. For example, the following code prints the values of two variables, but the order of the prints is reversed when the defer statement is used:

var a = 10
var b = 20

func printValues() {
    fmt.Println(a)
    fmt.Println(b)
}

func main() {
    defer printValues()

    a = 100
    b = 200

    printValues()
}

In this example, the printValues() function is called twice. The first time the function is called, the value of a is printed, followed by the value of b. The second time the function is called, the value of b is printed, followed by the value of a. This is because the deferred statement is executed after the printValues() function returns.

Conclusion

Defer is a powerful tool that can be used to delay the execution of statements until the end of the current function. This can be useful for performing cleanup tasks, controlling the order of execution, or logging errors.