Junior — Middle
Can you explain the principle of operation and application of the defer construct in Go?
sobes.tech AI
Answer from AI
In Go, the keyword defer is used to schedule a function call to be run after the function completes — it will be executed at the moment of exiting the current function, regardless of how the exit occurs (normal or due to an error). This is convenient for releasing resources, closing files, unlocking mutexes, and other cleanup operations.
Example:
func readFile(filename string) error {
file, err := os.Open(filename)
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 write cleaner and safer code, ensuring that important cleanup actions are performed.