I have a function that takes a &Vector<T>
. I want to change it to take an iterator in order to run it on different container/collection/slice types.
It produces an error because the function is called twice.
What I Have So Far
fn operate_on_iterator<'a>(iterator: &impl IntoIterator<Item = i32>) -> i32 {
// This is an example. Please don't tell me to use `.sum`.
let mut sum = 0;
for val in iterator.into_iter() {
sum += val;
}
sum
}
fn caller() -> i32 {
let v = vec![1, 2, 3, 4];
let s1 = operate_on_iterator(&v);
let s2 = operate_on_iterator(&v);
s1 + s2
}
The Error I Get
error[E0507]: cannot move out of `*iterator` which is behind a shared reference
--> src/lib.rs:13:16
|
13 | for val in iterator.into_iter() {
| ^^^^^^^^ move occurs because `*iterator` has type `impl IntoIterator<Item = i32>`, which does not implement the `Copy` trait
Restrictions and notes
- I do not want to use
dyn
because I prefer the slightly larger code size over the performance impact of pointer dereferencing. (Although I will use it for now and will benchmark it once I have both traits and trait objects implemented, i.e. after I have an answer to this question.) Also usingdyn
also didn't work so far for me. - I have used this answer as a basis. How to write a Rust function that takes an iterator?
- My
Item
implementsClone
,Binding
, andDrop
. - I also tried to implement it using
Iterator
instead ofIntoIterator
. Also no luck.