Middle
What is defer in Go and when is it called?
sobes.tech AI
Answer from AI
In Go, the keyword defer is used to schedule a function call to be run after the surrounding function completes, but before it exits.
This is convenient for releasing resources, closing files, unlocking mutexes, and other cleanup operations, ensuring they happen even if errors or panics occur.
Example:
func readFile() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer file.Close() // the file will be closed at the end of the function
// work with the file
}
Here, file.Close() will be called automatically when readFile exits, regardless of how the function terminates.