Pass variables to closure
Description
By default, closures capture their environment by borrowing. Or you can use a
move
-closure to move the whole environment. However, often you want to move
just some variables to the closure, give it a copy of some data, pass by
reference, or perform some other transformation.
Use variable rebinding in a separate scope for that.
Example
Use
instead of
Advantages
Copied data are grouped together with the closure definition, so their purpose is more clear, and they will be dropped immediately even if they are not consumed by the closure.
The closure uses the same variable names as the surrounding code, whether data are copied or moved.
Disadvantages
Additional indentation of the closure body.