I have ownership of an array of size 3 and I would like to iterate on it, moving the elements out as I go. Basically, I would like to have IntoIterator
implemen
Using the non-lexical lifetimes feature (only in nightly) and a fixed-length slice pattern you can move out of an array:
#![feature(nll)]
#[derive(Debug)]
struct Foo;
fn bar(foo: Foo) {
println!("{:?}", foo);
}
fn main() {
let v: [Foo; 3] = [Foo, Foo, Foo];
let [a, b, c] = v;
bar(a);
bar(b);
bar(c);
}
However, this solution does not scale well if the array is big.
An alternative, if you don't mind the extra allocation, is to box the array and convert it into a Vec
:
fn main() {
let v: [Foo; 3] = [Foo, Foo, Foo];
let v = Vec::from(Box::new(v) as Box<[_]>);
for a in v {
bar(a);
}
}
If the array is very big, that may be an issue. But then, if the array is very big, you should not be creating it in the stack in the first place!