Defer in Golang
Amit Tiwary
Posted on January 20, 2024
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")
}
The output is
inside main function
inside main function first defer
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
}
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.
Posted on January 20, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.