Defer Statement
Start with Defer Statement
The defer statement schedules a function call to run when the surrounding function is about to return. It is commonly used for cleanup.
What you’ll learn
- Explain the main purpose of defer statement.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
The arguments to a deferred call are evaluated when the defer statement executes, even though the call runs later. Multiple deferred calls run in last-in, first-out order.
defer is useful for closing open files and releasing resources after successful acquisition. It belongs near the operation that acquires the resource. A deferred function runs when its surrounding function returns, not at the end of an arbitrary brace-delimited block.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func example() {
message := "first value"
defer fmt.Println("Deferred:", message)
defer fmt.Println("Cleanup second")
message = "updated value"
fmt.Println("Body:", message)
}
func main() { example() }
Output
Body: updated value
Cleanup second
Deferred: first valueTrace what the program does
Both defers are registered before the body print. The first defer captures the current string value first value immediately. The body prints updated value. On return, Cleanup second runs first, followed by the earlier deferred print showing first value.
Avoid common mistakes
- Deferred calls in a function run in reverse registration order.
- Do not defer cleanup before confirming that a resource was acquired successfully.
Try it yourself
Add a third deferred print at the beginning of example and write down the exact order of all four output lines.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Defer Statement in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.