All lessons

Power Tools: Closures & Iterators

10 min · Rust

Write inline closures and transform vectors with .map() and .filter().

Rust · Power Tools: Closures & Iterators0/5 cleared

Enemy 1 of 5

A closure is a small, unnamed function you can define right where you need it, without a separate fn declaration. The syntax is |params| expression: pipes instead of parentheses around the parameter list, then the expression the closure evaluates. You can assign a closure to a variable and call it exactly like a regular function — square(6) works the same whether square was defined with fn or as a closure.

Closures are called "closures" because they can close over — capture — variables from the surrounding scope, something an ordinary named function can't do as naturally. That capturing ability is what makes them so useful for the short, throwaway logic you hand to functions like .map() and .filter() below: instead of writing a whole separate named function for a one-line transformation, you write the logic inline, right where it's used.

You
Binary Treant

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 36