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) withdefernear the opening point. - Predict LIFO order of more
deferand immediate evaluation of their arguments. - Avoid resource leaks caused by
deferplaced inside longforloops and understand controlled recovery withrecover().
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
- 1Cleanup near acquisition
- 2Topics evaluated immediately, LIFO order on exit
- 3
defer+recover()versuspanic - 4Classic trap:
deferinside a loop - 5Guided practice
- 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.