go

Defer in Golang

amitiwary999

Amit Tiwary

Posted on January 20, 2024

Defer in Golang

In my last blog I used defer function and use resolve inside it. defer is one of the important feature of golang. defer statement execute just before the function, in which defer added, returns.

One of the main uses of a defer statement is to clean resources like network connection, open files etc. After program is done with these resources then these resources should be closed to avoid program limit exhaustion and the resource wastage. In last blog recover is added inside defer function that make sure that if program panic then before exit defer statement execute and recover from panic. Take below code as an example.

func TryPanic() {
    defer func() {
        fmt.Println("inside main function first defer")
        recover()
    }()
    fmt.Println("inside main function")
    panic("panic in main")
}
Enter fullscreen mode Exit fullscreen mode

The output is

inside main function
inside main function first defer
Enter fullscreen mode Exit fullscreen mode

This function panic still program doesn’t exit because we have recover inside defer.

Example of free up resource after the use

func createFile() error {
    file, err := os.Create("inside-defer.txt")
    defer file.Close()
    if err != nil {
        fmt.Println("failed to create file")
    return err
    }
  _, err = io.WriteString(file, text) 
  if err != nil {
    fmt.Println("failed to write to file")
    return err
  }
 return nil
}
Enter fullscreen mode Exit fullscreen mode

Once we are done with the file and before the program exit, it’s important to close the file so that resource can be saved.

We can add multiple defer statement in a function although single defer statement can work. Multiple defer statement can helps to write the readable code where we clean different resource in separate defer statement. The multiple defer statement execute in LIFO order i.e that last defer execute first.

💖 💪 🙅 🚩
amitiwary999
Amit Tiwary

Posted on January 20, 2024

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

Sign up to receive the latest update from our blog.

Related

Where GitOps Meets ClickOps
devops Where GitOps Meets ClickOps

November 29, 2024

How to Use KitOps with MLflow
beginners How to Use KitOps with MLflow

November 29, 2024