Closures and how they capture
A closure is written `|args| body` and can use variables from the surrounding scope. How it captures them is decided by what the body does: read only, mutate, or take ownership.
That decision is what the `Fn`, `FnMut` and `FnOnce` traits describe. A closure that only reads is `Fn`; one that mutates is `FnMut`; one that consumes what it captured is `FnOnce` and can be called just once.
The `move` keyword forces ownership into the closure. You need it whenever the closure outlives the scope it was written in — sending work to a thread, for example.
Run it and change it
The editor below is live: edit anything and the real compiler output updates by itself.
Contrast AAA · 16.6:1
15px