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.
Top comments (2)
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!!
Thanks for sharing your experience. It will help everyone including me.