DEV Community

Cover image for Defer in Golang
Amit Tiwary
Amit Tiwary

Posted on

Defer in Golang

#go

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.

Top comments (2)

Collapse
 
syxaxis profile image
George Johnson

I will jonkingly add, just be self aware on "defer". In my early Go journey I got hooked on defers to make the code sharp and efficient on resources, I used them all the time, but I once spent 3 hours debugging why my DB and stream handles were closed when i needed them and realised I'd gone "defer blind" it was closing my open handles for me but I couldn't see my defers! Ha ha!!

Collapse
 
amitiwary999 profile image
Amit Tiwary

Thanks for sharing your experience. It will help everyone including me.