The “defer” keyword in GoLang


In GoLang, the defer keyword is used to ensure that a function call is performed later in a program’s execution, typically for purposes of cleanup. Deferred function calls are executed in last-in-first-out order just before the surrounding function returns. This makes defer especially useful for releasing resources, such as closing a file or unlocking a mutex, which ensures that the cleanup code is run no matter how the function exits.

A function being called “defer” is like the “async” but postponed and without the await. It is one of the Asynchronous Programming.

Here is a detailed explanation of how defer works and some examples to illustrate its usage:

Key Characteristics of defer keyword

Execution Order: Deferred function calls are pushed onto a stack. Each time a defer statement is encountered, the deferred function call is added to the stack. When the surrounding function returns, the deferred calls are executed in reverse order (last-in, first-out).

Arguments Evaluation: The arguments to a deferred function call are evaluated immediately when the defer statement is executed, not when the actual call is executed.

Common Use Cases of the defer keyword in GoLang

  • Resource Management: Ensuring resources like files or network connections are properly closed.
  • Panic Recovery: Deferring a function that handles a potential panic to ensure the program can clean up before crashing.

Examples of the defer in GoLang

Example 1: Basic defer Usage

package main

import (
    "fmt"
)

func main() {
    fmt.Println("start")
    defer fmt.Println("middle")
    fmt.Println("end")
}

Output:

start
end
middle

In this example, the call to fmt.Println(“middle”) is deferred and thus executed after fmt.Println(“end”).

Example 2: Closing a File

package main

import (
    "fmt"
    "os"
)

func main() {
    f, err := os.Open("file.txt")
    if err != nil {
        fmt.Println(err)
        return
    }
    defer f.Close()

    // Perform file operations
}

In this example, f.Close() is deferred, ensuring that the file is closed when main returns, even if an error occurs or a return statement is hit before the end of the function.

Example 3: Deferred Functions and Arguments

package main

import "fmt"

func main() {
    x := 10
    defer fmt.Println("deferred x:", x)
    x = 20
    fmt.Println("current x:", x)
}

Output:

current x: 20
deferred x: 10

In this example, the deferred function captures the value of x at the time the defer statement is executed, not when the deferred function is actually called.

Advanced Example: Multiple Deferred Functions

package main

import "fmt"

func main() {
    defer fmt.Println("first")
    defer fmt.Println("second")
    defer fmt.Println("third")
    fmt.Println("main function")
}
main function
third
second
first

Here, each defer statement adds a function call to a stack, which are then executed in last-in-first-out order.

TLDR; Conclusion of GoLang defer keyword

The defer keyword in Go is a powerful feature for managing resources and ensuring cleanup actions are performed. Its stack-based execution order and immediate evaluation of arguments provide a predictable and structured way to handle finalization logic in your programs.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
639 words
Last Post: Best Security Practices for Holding Cryptocurrencies on Exchanges
Next Post: Teaching Kids Programming - Introduction to SQL Join Queries (Inner, Left, Right, Full and Cross Joins)

The Permanent URL is: The “defer” keyword in GoLang

Leave a Reply