"Defer" Keyword in Golang

cyborglaksh

Lakshgupta

Posted on June 10, 2023

"Defer" Keyword in Golang

Most of the Developers are switching to the recently developed Golang tech by Google in 2009 because of its code efficiency and less execution time as it is a compiled language.

Will talk about an important keyword used in Golang "Defer" in this article..

Defer is used for some bytes of code if a prior cleanup is required for the function created in Golang before its return.
With the help of "defer" keyword, we can have optimized code promoting more robust and reliable code.

*Defer makes the statement fall at a position in stack that the code after the keyword just takes execution just before the function is returned.
*

Defer Keyword contributes to enhance the code in following ways:

  • Cleanup of Code
  • To lock the opened results
  • Close opened files to make code reliable.

Refer the code for the same & understand the steps of execution by the summary below :

package main

import (
    "fmt"
    "os"
)

func main() {
    file := createFile("example.txt")
    defer closeFile(file)

    writeToFile(file, "Hello, Golang!")
}

func createFile(filename string) *os.File {
    fmt.Println("Creating file:", filename)
    file, err := os.Create(filename)
    if err != nil {
        panic(err)
    }
    return file
}

func writeToFile(file *os.File, message string) {
    fmt.Println("Writing to file:", message)
    _, err := file.WriteString(message)
    if err != nil {
        panic(err)
    }
}

func closeFile(file *os.File) {
    fmt.Println("Closing file")
    err := file.Close()
    if err != nil {
        panic(err)
    }
}

Enter fullscreen mode Exit fullscreen mode

In this piece of Code because of we using defer keyword the function just before returning closes the opened file and hence make no mistake & no misplace of any data.

Defer is a keyword defined its use in the Golang Documentation.
Refer to the documentation to understand more and learn implementation:

💖 💪 🙅 🚩
cyborglaksh
Lakshgupta

Posted on June 10, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related