Senior
What does the keyword defer mean in Go?
sobes.tech AI
Answer from AI
The keyword defer in Go is used for deferred function calls — it will be executed after the surrounding function completes, but before it returns.
This is convenient for releasing resources, closing files, unlocking mutexes, etc., ensuring execution even in case of errors or panics.
Example:
func readFile(filename string) error {
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close() // Will close when exiting the function
// Work with the file
// ...
return nil
}
Thus, defer helps write clean and safe code, managing resources neatly and predictably.