Explain the use of Go's defer statement for scheduling function calls to be executed later?
In Go, the defer statement is used to schedule a function call to be executed just before the function it's declared in returns. This is often used for cleanup tasks or for tasks that need to be performed after a function has completed, regardless of whether an error occurred or not.
The **defer**
statement can be used to schedule multiple function calls, and they are executed in a last-in, first-out (LIFO) order. This means that the most recently scheduled function call is executed first, and the first scheduled function call is executed last.
The **defer**
statement can be useful in a number of situations, such as:
- Closing resources, such as files or network connections
- Unlocking mutexes or releasing other synchronization primitives
- Logging errors or other information
- Recovering from panics
Here is an example of using **defer**
to close a file:
func readFile(filename string) ([]byte, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
return ioutil.ReadAll(f)
}
In this example, the **os.Open**
function is used to open a file, and if an error occurs, it's returned immediately. If the file is successfully opened, a **defer**
statement is used to schedule a call to the **Close**
method on the file, which will be executed just before the function returns. Finally, the **ioutil.ReadAll**
function is used to read the contents of the file and return them.
Using **defer**
in this way ensures that the file will always be closed, even if an error occurs while reading the contents.