What is defer?
Defer is a special keyword in the Go programming language that tells the program to run a piece of code later, just before the current function finishes executing.
Let's break it down
When you write defer someFunction()
inside a function, Go remembers that call. No matter how the function ends-whether it reaches the end, returns early, or panics-Go will automatically call someFunction()
right before leaving the function.
Why does it matter?
Defer makes it easy to clean up resources (like closing files, unlocking mutexes, or releasing network connections) without having to write the cleanup code at every possible exit point. It helps keep code tidy and reduces bugs caused by forgotten cleanup steps.
Where is it used?
- Closing files after reading or writing them.
- Unlocking a mutex after a critical section.
- Sending a signal or logging when a function is done.
- Recovering from panics to keep the program running.
Good things about it
- Guarantees cleanup code runs, even on early returns or errors.
- Improves readability by keeping the setup and cleanup close together.
- Simple syntax: just add
defer
before a function call. - Supports multiple defer statements; they run in last‑in‑first‑out order.
Not-so-good things
- Each defer adds a small runtime overhead, which can matter in tight loops or performance‑critical code.
- The deferred function’s arguments are evaluated immediately, which can be surprising if you expect lazy evaluation.
- Overusing defer in hot paths may lead to slower code compared to manual cleanup.