How to Use the defer Keyword in Go

The defer keyword in Go schedules a function call to run immediately before the surrounding function returns, ensuring reliable resource cleanup.

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
}