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
The core thing you would need is some way of getting the value out of the array without moving it. Two such solutions are:
Use mem::replace and mem::uninitialized to replace each value in the array with garbage, getting the original back:
let one = unsafe { mem::replace(&mut v[0], mem::uninitialized()) };
bar(one);
Use ptr::read to leave the value in the array but get an owned value back:
let two = unsafe { ptr::read(&v[0]) };
bar(two);
It's just a matter of doing one of these a few times in a loop and you are good to go.
There's just one tiny problem: you see those unsafe
? You guessed it; this is totally, horribly broken in the wider case:
Foo
. In this case, nothing special happens when that array goes out of scope as there's no special Drop
implementation for the type Foo
, but if there was, it would be accessing invalid memory. Bad news! bar
function), the array will be in a partially-uninitialized state. This is another (subtle) path where the Drop
implementation can be called, so now we have to know which values the array still owns and which have been moved out. We are responsible for freeing the values we still own and not the others. The right solution is to track how many of the values in the array are valid / invalid. When the array is dropped, you can drop the remaining valid items and ignore the invalid ones. You also have to avoid the automatic destructor from running. It'd also be really nice if we could make this work for arrays of different sizes...
Which is where arrayvec comes in. It doesn't have the exact same implementation (because it's smarter), but it does have the same semantics:
extern crate arrayvec;
use arrayvec::ArrayVec;
#[derive(Debug)]
struct Foo;
fn bar(foo: Foo) {
println!("{:?}", foo)
}
fn main() {
let v = ArrayVec::from([Foo, Foo, Foo]);
for f in v {
bar(f);
}
}
In nightly Rust, you can use std::array::IntoIter to get a by-value array iterator:
#![feature(array_value_iter)]
use std::array::IntoIter;
fn main() {
let v: [Foo; 3] = [Foo, Foo, Foo];
for a in IntoIter::new(v) {
bar(a);
}
}
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!
You may use array of Option<Foo>
instead array of Foo
. It has some memory penalty of course. Function take() replaces value in array with None
.
#[derive(Debug)]
struct Foo;
// A method that needs an owned Foo
fn bar(foo: Foo) { println!("{:?}", foo); }
fn main() {
let mut v = [Some(Foo),Some(Foo),Some(Foo)];
for a in &mut v {
a.take().map(|x| bar(x));
}
}