What is a defer statement in Go? When would you use it?

In Go, a defer statement is used to schedule a function call to be executed immediately before the surrounding function or block returns. The defer statement is typically used to ensure that resources like files, database connections, and network connections are released or closed properly when a function returns, even if the return statement is caused by an error.

The syntax for defer statement is as follows:

scss
defer funcName(args)

Here, funcName is the name of the function to be called and args are the arguments to be passed to the function. The defer statement should be placed immediately after the statement that creates the resource that needs to be cleaned up, such as opening a file or a database connection.

For example, let’s say you have a function that opens a file, reads its contents, and then closes the file. You can use a defer statement to ensure that the file is closed properly even if an error occurs while reading its contents:

func readFromFile(filename string) ([]byte, error) {
    file, err := os.Open(filename)
    
   if err != nil {

        returnnil, err
 }
   
     defer file.Close() // This statement ensures that the file is closed before the function returns
     data, err := ioutil.ReadAll(file)

    
    if err != nil {

        returnnil, err
   }
   
return data, nil
}

In this example, the defer file.Close() statement is executed when the readFromFile function returns, regardless of whether an error occurred or not. This ensures that the file is closed properly, preventing any potential resource leaks.

Leave a Reply

Your email address will not be published. Required fields are marked *

2 + 4 =

Related Post