Middle
What is the defer operator in Go language?
sobes.tech AI
Answer from AI
The defer operator is used for deferred execution of a function or method. Functions marked with defer are executed immediately before exiting the function that contains them.
Principles of defer operation:
- Executed upon exiting the current function, whether normally or due to a panic.
- Multiple
deferstatements in one function are executed in LIFO (Last-In, First-Out) order. - Useful for cleaning up resources, such as closing files or network connections.
Example of usage:
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("Opening file.")
file, err := os.Open("example.txt")
if err != nil {
// Error handling
return
}
// Deferred closing of the file
defer file.Close()
defer fmt.Println("File will be closed.") // This defer will execute first (LIFO)
fmt.Println("Processing the file...")
// Further work with the file
}
Program output:
Opening file.
Processing the file...
File will be closed.