Defer Keyword in Golang

Defer Keyword in Golang

Table of contents

No heading

No headings in the article.

The defer keyword in Golang is used to execute a function call after the current function has finished executing. This can be useful for things like closing files, releasing resources, or performing cleanup tasks.

The defer keyword is always executed, even if an error occurs in the current function. This makes it a safe way to ensure that important tasks are always completed, even if something goes wrong.

Here is an example of how to use the defer keyword to close a file:

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

    // Defer the closing of the file
    defer f.Close()

    // Read the contents of the file
    b, err := ioutil.ReadAll(f)
    if err != nil {
        fmt.Println(err)
        return
    }

    // Print the contents of the file
    fmt.Println(string(b))
}

In this example, the f.Close() function call will be executed after the main() function has finished executing. This ensures that the file is always closed, even if an error occurs in the main() function.

The defer keyword can also be used to execute multiple function calls. For example:

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

    // Defer the closing of the file
    defer func() {
        f.Close()
        fmt.Println("File closed")
    }()

    // Read the contents of the file
    b, err := ioutil.ReadAll(f)
    if err != nil {
        fmt.Println(err)
        return
    }

    // Print the contents of the file
    fmt.Println(string(b))
}

In this example, the f.Close() function call and the fmt.Println("File closed") function call will both be executed after the main() function has finished executing.

The defer keyword is a powerful tool that can be used to ensure that important tasks are always completed, even if an error occurs. It is a useful feature of the Go programming language that can help you to write more reliable code.