By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
Some code must run at the end of a function no matter how the function ends: closing a file, releasing a lock, printing a summary. defer schedules a function call to run when the surrounding function returns. You write defer in front of the call at the point where the work starts, and Go runs the call on the way out.
The defer line itself does not run the call. It records it, and the body keeps going. That is what makes defer useful for clean-up: you set it up next to the resource, then forget about it.
Several defers in one function run in reverse order. Go keeps deferred calls on a stack: the last one deferred is the first one run. The name for that order is LIFO, last in, first out.
package main
import "fmt"
func main() {
fmt.Println("open the ledger")
defer fmt.Println("close the ledger")
defer fmt.Println("save the totals")
defer fmt.Println("release the lock")
fmt.Println("add three expenses")
}Read the output from the bottom back up: the last defer printed first after the body, then the middle one, then the first. This is why defer pairs naturally: the thing opened first is closed last.
A defer records the call and its arguments at the moment the defer statement runs. Only the call itself is postponed. If a variable changes after the defer line, the deferred call still uses the value it had when the defer was written.
package main
import "fmt"
func main() {
total := 1250
defer fmt.Println("deferred total:", total)
total = 4200
fmt.Println("current total:", total)
}The deferred line printed 1250, not 4200, although it ran after the assignment. If you want the deferred work to see the latest value, defer a closure that reads the variable when it runs. That combines the previous lesson with this one.
A function can return from several places, including a guard clause early in the body. A defer runs on every one of those exits, which makes it a reliable place for clean-up even when a check sends the function home early.
package main
import "fmt"
func checkAmount(cents int) {
defer fmt.Println("done checking", cents)
if cents <= 0 {
fmt.Println("invalid amount")
return
}
fmt.Println("valid amount")
}
func main() {
checkAmount(0)
checkAmount(1250)
}Both calls print their done checking line: the first after the early return, the second after the normal end. The defer does not care which return path was taken, which is exactly what you want for closing something you opened.
The most common real use of defer is closing a file. You open the file, defer the close on the next line, and then read or write without worrying about every return path. Step 33 uses the real file version; here is the shape with a function that stands in for an open ledger.
package main
import "fmt"
func openLedger(name string) func() {
fmt.Println("open", name)
return func() {
fmt.Println("close", name)
}
}
func main() {
closeLedger := openLedger("penny.json")
defer closeLedger()
fmt.Println("append an expense")
fmt.Println("append another expense")
}openLedger returns a small closure that prints the close message. defer closeLedger() registers it, and the close message appears after the two append lines. When you meet f, err := os.Open(...) later, the pattern is the same: check the error, then defer the close on the next line.
Add two more deferred calls to the first program in this lesson and write down the full order before you run it. Then put a defer inside a function that returns early and confirm the deferred line still runs. Keep one habit from this lesson: write defer on the line right after the thing it cleans up, while you still remember what needs cleaning.
Key takeaways
defer schedules a function call to run when the surrounding function returns.
Several deferred calls run last in, first out: the most recent defer runs first.
Arguments to a deferred call are evaluated when the defer statement runs, not when the call runs.
A defer runs on every return path, including early returns and guard clauses.
Use defer close() immediately after you open or acquire something.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.