ProgramGuru

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.

Visual explanation for deferDeferred calls run when the surrounding function returns.Register defer AStep 1Register defer BStep 2Execute bodyStep 3Run B, then AStep 4Deferred calls run when the surrounding function returns.
Deferred calls run when the surrounding function returns.

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 value

Trace 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

When are the arguments of a deferred call evaluated?
Choose one answer. You can try again.

Answer and explanation

When defer executes

Correct. Both defers are registered before the body print.

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.

    Next lesson: Arrays →