The defer keyword schedules a function call to execute immediately before the surrounding function returns, ensuring cleanup tasks run even if the function exits early or panics. It is commonly used to close files, release locks, or restore state.
func processFile(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close() // Executes before processFile returns
// ... process file ...
return nil
}