25% off

Use code FUNCMAIN at checkout for 25% off all premium courses.

Get started →

Interactive Go · Lesson

Defer

defer schedules a call to run when the surrounding function returns — perfect for cleanup you don’t want to forget (closing a file, releasing a lock, snuffing a torch).

func readScroll() {
    defer fmt.Println("scroll rolled back up")
    fmt.Println("reading the scroll...")
}

Deferred calls run in LIFO order — the last one deferred runs first. So if you defer two things, they unwind in reverse.

Your Quest

Add a deferred print of Torch extinguished. Because deferred calls run last and in reverse order, the output should be:

You enter the chamber.
Torch extinguished.
The door closes behind you.

Hint

Add defer fmt.Println("Torch extinguished.") on the commented line. It was deferred after the door line, so it runs before it.

Additional Scrolls of Wisdom