Editor\'s note: This question was asked before Rust 1.0 and some of the syntax has changed since then, but the underlying concepts remain. Some answers have b
It is possible to collect
multiple closures from an iterator into a Vec
:
fn main() {
let a: Vec<_> = (0..10).map(|i| move || i).collect();
println!("{} {} {}", a[1](), a[5](), a[9]());
}
The move
keyword causes ownership of i
to be transferred to the closure.
See also:
You need to use move || i
.
move
implies that this closure will take i
by value rather than by reference. By default, these closures would only take references to i
. In your case it is forbidden as the lifetime of i
is limited to the body of the loop.
Also, Rust will complain that your array may not be fully initialized. To avoid it, you can either use a Vec<_>
, or use std::mem::uninitialized
:
fn main() {
let mut a: [_; 10] = unsafe { std::mem::uninitialized() };
for i in 0..10 {
a[i] = move || i;
}
println!("{} {} {}", a[1](), a[5](), a[9]())
}