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
implemented for a fixed-sized array.
Since arrays don't implement this trait in the standard library (I understand why), is there a workaround to get the desired effect? My objects are not Copy
nor Clone
. I'd be okay creating a Vec
from the array and then iterating into the Vec
, but I'm not even sure how to do that.
(For information, I'd like to fulfill an array of Complete
)
Here is a simple example of the situation (with a naive iter()
attempt):
// No-copy, No-clone struct
#[derive(Debug)]
struct Foo;
// A method that needs an owned Foo
fn bar(foo: Foo) {
println!("{:?}", foo);
}
fn main() {
let v: [Foo; 3] = [Foo, Foo, Foo];
for a in v.iter() {
bar(*a);
}
}
Gives
error[E0507]: cannot move out of borrowed content
--> src/main.rs:14:13
|
14 | bar(*a);
| ^^ cannot move out of borrowed content
See Question&Answers more detail:os