Using Defer
The defer keyword schedules a function call to run immediately before the surrounding function returns.
Common Use Case: Closing Files/Connections
go f, err := os.Open("file.txt") if err != nil { return err } defer f.Close() // Guaranteed to run at the end
// Read from file...
This prevents resource leaks, which is critical for microservices running for months.