Go by Example: Defer

The defer statement in Go schedules a function call to be executed immediately before the function it is called in returns. The defer statement is often used to ensure that resources are properly cleaned up, even if the function returns early due to an error. Here’s an example of using defer:

package main

import (
	"fmt"
	"os"
)

func main() {
	file, err := os.Open("file.txt")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	defer file.Close()

	// Read the file contents
	// ...
}

In this example, the os.Open function is used to open a file named "file.txt". If the file cannot be opened, an error message is printed and the function returns early. The defer statement schedules the call to file.Close to be executed immediately before the function returns, ensuring that the file is closed even if the function returns early due to an error. This is especially useful in longer functions, where it can be easy to forget to clean up resources when returning early. With defer, the cleanup is guaranteed to be performed, regardless of how the function returns.


Comments

Leave a Reply

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