Go Tutorial: Closures and Defer
Anonymous functions, closures that remember state, defer for reliable cleanup, and a first look at panic and recover.
Functions that remember
In the Functions chapter you learned to name a piece of code and call it. Now you will see that functions are even more flexible than that.
A function can be written on the spot, without a name. It can reach out and use the variables around it, and keep using them long after the code that created it has finished. That is a **closure**, and it is how Go code keeps small pieces of private state, like a ticket counter at the library desk.
Then comes `defer`: a way to say "do this when the function is done", no matter how it finishes. It is the standard way to make sure cleanup always happens, like closing the ledger at the end of the day.
Finally, you will take a first look at `panic` and `recover`, Go's emergency stop and the way to catch it.
What you'll learn in this Go closures and defer tutorial
This interactive Go tutorial has 10 hands-on exercises. Estimated time: 26 minutes.
- Functions are values (quick recap) — In the Functions chapter you saw that a function is a value, just like an int or a string. You can store it in a variabl…
- Anonymous functions — A function does not need a name. You can write `func(...) { ... }` right where you need it and store it in a variable, w…
- Closures remember their surroundings — An anonymous function can use the variables of the function it was written in. It does not get a copy: it shares the var…
- A ticket counter factory — A function can also **return** a closure. The captured variables live on after the outer function has returned, and ever…
- Each loop iteration gets its own variable — Closures created inside a loop capture the loop variable. Since Go 1.22, every iteration gets a **fresh** copy of that v…
- defer: do it on the way out — `defer` schedules a function call to run when the surrounding function returns, no matter where in the function the `def…
- Stacked defers run in reverse — When a function defers several calls, they run in **last-in, first-out** order, like a stack of books: the last one you …
- defer for cleanup — The most common use of `defer` is cleanup: closing a file, releasing a lock, or here, closing the library ledger. Writin…
- panic and recover — A **panic** is Go's emergency stop. It happens on serious bugs, like indexing past the end of a slice, or when you call …
- Recover from a missing shelf slot — `pickBook(shelf, 5)` asks for a slot that does not exist, so `shelf[i]` panics and crashes the program. Run it first if …
Go Closures and Defer concepts covered
- Functions that remember