Re:Rust 1.0: Status report and final timeline
by aturon on Friday February 13, 2015 @05:59PM
(#9047766)
> The way variables are captured from the environment into the closure is controlled by the "move" keyword. If the "move" keyword precedes a closure expression, then variables from the environment are moved into the closure, which takes ownership of them.
Note: if you don't specify `move`, then the captures are determined in the usual way:
`|| v.len()` captures `v` via an immutable borrow
`|| v.push(0)` captures `v` via a mutable borrow
`|| v.into_iter()` captures `v` by moving it
Re:Rust 1.0: Status report and final timeline
by mbrubeck on Friday February 13, 2015 @05:49PM
(#9047722)
Thanks for the correction.
Re:Rust 1.0: Status report and final timeline
by tomjakubowski on Friday February 13, 2015 @06:11PM
(#9047804)
Fortunately with the annotations gone, I think there will be a lot less confusion! The "move" keyword on its own is pretty straightforward, at least once you've learned Rust's ownership model.
That particular annotation controlled the access a closure has to its environment, not how it's captured. |&:|, |&mut: |, and |:| corresponded to the Fn, FnMut, and FnOnce traits, respectively. If you look at the signatures of those traits, you'll see that Fn's method takes self by reference, FnMut takes it by mutable reference, and FnOnce takes it by value. In particular, this means that the body of an FnOnce closure can move values out from the closure (that's why it can only be called once), whereas Fn and FnMut can only access values in the closure by reference and mutable reference, respectively.
The way variables are captured from the environment into the closure is controlled by the "move" keyword. If the "move" keyword precedes a closure expression, then variables from the environment are moved into the closure, which takes ownership of them. "move" is usually associated with FnOnce closures, but it's also needed when returning a boxed Fn or FnMut closure from a function, as you can see below: