defer
In Go, the defer
statement is used to postpone the execution of a function until just before the containing function returns. This feature is commonly utilized for cleanup tasks. Below is an example demonstrating how defer
is employed to close a file:
package main
import "os"
func main() {
f, err := os.Open("input.txt")
if err != nil {
log.Fatal(err)
}
defer f.Close()
}
In this example, defer f.Close()
ensures that the Close
method on f
is called when the main
function finishes execution, regardless of whether it exits normally or due to an error. This guarantees that the file is properly closed, preventing resource leaks.