Skip to main content
Module 3 · Lesson 5 of 515/50 in the course~12 min
Module lessons (5/5)

`defer`: guaranteed cleanup

Lesson preview5 hands-on exercises readyCourse Go · Module 3 — Functions

Postpone execution until return; pattern defer f.Close(), LIFO order, gotcha with loops.

What you'll learn in this lesson

  • Ensure closing resources (file, mutex, connections) with defer near the opening point.
  • Predict LIFO order of more defer and immediate evaluation of their arguments.
  • Avoid resource leaks caused by defer placed inside long for loops and understand controlled recovery with recover().

Overview

The defer instruction schedules a function call to execute automatically right before the containing function returns, regardless of the exit path (return normal or panic).

recover() works only if called directly inside a function executed via defer: it intercepts the panic in progress and prevents the entire program from crashing.

Sections covered in this lesson

  1. 1Cleanup near acquisition
  2. 2Topics evaluated immediately, LIFO order on exit
  3. 3defer + recover() versus panic
  4. 4Classic trap: defer inside a loop
  5. 5Guided practice
  6. 6Check for understanding
Pro Lesson · Module 3 — Functions

Unlock "`defer`: guaranteed cleanup" and the full Course Go curriculum

Postpone execution until return; pattern `defer f.Close()`, LIFO order, gotcha with loops.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course Go plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.