Capturing
A closure can capture variables from the environment where it was defined.
Speaker Notes
This slide should take about 5 minutes.
-
By default, a closure captures values by reference. Here
max_value
is captured byclamp
, but still available tomain
for printing. Try makingmax_value
mutable, changing it, and printing the clamped values again. Why doesn’t this work? -
If a closure mutates values, it will capture them by mutable reference. Try adding
max_value += 1
toclamp
. -
You can force a closure to move values instead of referencing them with the
move
keyword. This can help with lifetimes, for example if the closure must outlive the captured values (more on lifetimes later).This looks like
move |v| ..
. Try adding this keyword and see ifmain
can still accessmax_value
after definingclamp
. -
By default, closures will capture each variable from an outer scope by the least demanding form of access they can (by shared reference if possible, then exclusive reference, then by move). The
move
keyword forces capture by value.