Golang program that uses defer keyword

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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()
}

chevron_right





My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.