Go defer

The defer statement schedules a function call to run when the surrounding function returns. Deferred calls execute in last-in, first-out order, making defer useful for cleanup such as closing files or releasing resources.

Minimal example

go
func printOrder() {
    defer fmt.Println("third")
    defer fmt.Println("second")
    fmt.Println("first")
}

Learn this concept

Lesson 1.4 · Go basics: types, functions and defer

Used in exercises

Exercise 1.8 · Practice: write your first Go program
Prerequisite conceptsGo functionsGo control flow