Open In App

Golang program that uses defer keyword

Improve
Improve
Like Article
Like
Save
Share
Report

The main use of the defer keyword in go is that it is used to clean up the resources used by opened files, network connections, database handles, etc. This helps to reduce the chances of error by keeping the call to close function/files nearer to call to open statements. The statement that is followed by defer keyword is placed onto a stack and in the end, they are called according to the last-in first-out(LIFO) order.

Example:




package main
  
import "fmt"
  
func main() {
    defer fmt.Println("First")
    defer fmt.Println("Second")
    fmt.Println("Last")
}


Output:

Last
Second
First

Here, you can see the statements are printed according to the LIFO. But, this is not what defer is made for so we will look on a program to understand the main use of defer keyword.

Example:

func write(fileName string, text string) error {
    file, err := os.Create(fileName)
    if err != nil {
        return err
    }
    _, err = io.WriteString(file, text)
    if err != nil {
        return err
    }
    file.Close()
    return nil
}

In this if the function io.WriteString fails then the program will return the error “err” and it will not be able to close the file, and this will result in wastage of resource, therefore here defer will be useful.

func write(fileName string, text string) error {
    file, err := os.Create(fileName)
    if err != nil {
        return err
    }

 // This statement will surely run at the end no 
 // matter what the program goes through.
  defer file.Close()
 
    _, err = io.WriteString(file, text)
    if err != nil {
        return err
    }

    return file.Close()
}

In this program, the statement defer file.Close() will run at the end of the function, if there is an error in the program then it will be able to close the file which was opened earlier in the program, and hence saving the resources. Below is the complete program for the same.




package main
  
import (
    "io"
    "log"
    "os"
)
  
func main() {
    if err := write("readme.txt", "This is a readme file"); err != nil {
        log.Fatal("failed to write file:", err)
          
    }
}
  
func write(fileName string, text string) error {
    file, err := os.Create(fileName)
    if err != nil {
        return err
    }
    defer file.Close()
    _, err = io.WriteString(file, text)
    if err != nil {
        return err
    }
  
    return file.Close()
}




Last Updated : 10 May, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads