Closures: Pocket Functions
What if you could write a tiny function right where you need it, pop it in your pocket, and use it later? Thatβs a closure β a little pocket-sized function. πͺ
A function you can save in a box
Normally a function gets a name and lives at the top of your file. A closure is different. You write it right inside your code and tuck it into a variable, like saving a handy shortcut to use again and again.
Closures use bars | | around their inputs instead of round brackets. Watch:
We made a closure called add_one. Whatever number you hand it, it gives back that
number plus one. Then we called it just like a normal function: add_one(5). π
Closures can peek at whatβs around them
Hereβs the powerful part: a closure can use variables from the area around it, even ones you didnβt pass in. It βcloses aroundβ them β thatβs why itβs called a closure!
We never handed bonus to the closure, but it grabbed it from nearby anyway. Handy! πͺ
| | are like little doorways where
your inputs walk in. If a closure takes nothing, just use empty bars: || 42.
add_one into double that does x * 2, then run
it with the number 8. What do you get?
Quick quiz
What does a closure use around its inputs?
Yes! Closures wrap their inputs in bars, like |x| x + 1. π
|x| x + 1, and it can even peek at variables nearby.
Next up: Iterators: Going Through Stuff β where closures really shine! π