Junior
What role does the defer construct play in Go?
sobes.tech AI
Answer from AI
In the Go language, the defer statement is used for deferred execution of a function — it will be called at the moment of exiting the current function, regardless of how the exit occurs (normally or due to an error).
This is convenient for releasing resources, closing files, unlocking mutexes, and other cleanup operations.
Example:
func readFile() error {
file, err := os.Open("file.txt")
if err != nil {
return err
}
defer file.Close() // the file will be closed when exiting the function
// work with the file
return nil
}
Thus, defer helps ensure the execution of important final actions, improving resource management and error handling.