How to Use defer in Go: Syntax, Examples, and Tips
In Go,
defer schedules a function call to run after the current function finishes, helping manage resources like files or locks. Use defer before a function call to ensure it executes last, even if the function returns early or panics.Syntax
The defer statement is followed by a function call. This call is postponed until the surrounding function completes. You can defer any function call, including anonymous functions.
- defer: keyword to delay execution
- function call: the function you want to run later
go
defer functionName(arguments)
Example
This example shows how defer is used to close a file after reading it. The defer ensures the file closes even if the function returns early.
go
package main import ( "fmt" "os" ) func readFile() { file, err := os.Open("example.txt") if err != nil { fmt.Println("Error opening file:", err) return } defer file.Close() // This will run when readFile returns buffer := make([]byte, 100) n, err := file.Read(buffer) if err != nil { fmt.Println("Error reading file:", err) return } fmt.Println("Read bytes:", n) } func main() { readFile() }
Output
Read bytes: 100
Common Pitfalls
One common mistake is deferring a function call with arguments that change later. The arguments are evaluated immediately when defer runs, not when the deferred function executes.
Also, multiple defer calls run in last-in, first-out order.
go
package main import "fmt" func main() { number := 5 defer fmt.Println("Deferred number:", number) // number is evaluated now number = 10 fmt.Println("Current number:", number) }
Output
Current number: 10
Deferred number: 5
Quick Reference
- defer delays a function call until the surrounding function returns.
- Arguments to deferred calls are evaluated immediately.
- Deferred calls execute in reverse order.
- Use defer to close files, unlock mutexes, or clean up resources.
Key Takeaways
Use
defer to run cleanup code after a function finishes, even if it returns early.Arguments in deferred calls are evaluated immediately, so be careful with variables that change.
Multiple deferred calls run in last-in, first-out order.
Common uses include closing files, unlocking resources, and logging.
Defer helps write cleaner and safer code by managing resource cleanup automatically.