The defer
keyword in Go is a powerful feature that allows you to schedule a function call to be run after the surrounding function returns. It's an essential tool for resource management and cleanup operations.
defer
pushes a function call onto a stack. When the surrounding function returns, its deferred calls are executed in last-in-first-out order. This mechanism ensures that resources are properly released, regardless of how a function exits.
To use defer
, simply place it before a function or method call:
defer functionCall()
defer
is often used to ensure files are closed after operations are complete:
func readFile(filename string) error {
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
// Read file contents
// ...
}
When working with Go Mutexes, defer
helps prevent deadlocks by ensuring locks are released:
func updateResource(m *sync.Mutex) {
m.Lock()
defer m.Unlock()
// Update shared resource
// ...
}
defer
statement is executed, not when the function is called.defer
for cleanup operations to ensure they're always executed.defer
statements near the resources they're managing for better readability.defer
in loops, as deferred calls don't execute until the function returns.To fully grasp the power of defer
, it's helpful to understand these related Go concepts:
By mastering defer
, you'll write more robust and maintainable Go code, ensuring proper resource management and cleaner function exits.