I have a generic function which is called recursively and which can take arguments that can be converted into an iterator.
I would like to chain the iterator which is passed as argument with the iterator created from a function local collection. The idea is that after calling the recursive function several times a single iterator is created which is able to iterate over all the collections living in their individual stack frame.
fn func_taking_iter<'a, I>(vals: I) -> ()
where
I: IntoIterator<Item = &'a u32>,
I::IntoIter: Clone,
{
let vals = vals.into_iter();
let mut new_val: [u32; 1] = [0u32; 1];
for x in vals.clone() {
new_val[0] = *x;
}
new_val[0] += 1u32;
if new_val[0] == 10u32 {
for x in vals {
println!("Value {}", *x);
}
return;
}
let res = vals.into_iter().chain(new_val.into_iter());
func_taking_iter(res);
}
fn main() {
let first_val = [0u32; 1];
func_taking_iter(first_val.iter());
}
Unfortunatly I get the following error when I try to compile the code.
error[E0597]: `new_val` does not live long enough
--> src\main.rs:20:38
|
1 | fn func_taking_iter<'a, I>(vals: I) -> ()
| -- lifetime `'a` defined here
...
20 | let res = vals.into_iter().chain(new_val.into_iter());
| -----------------------^^^^^^^-------------
| | |
| | borrowed value does not live long enough
| argument requires that `new_val` is borrowed for `'a`
...
23 | }
| - `new_val` dropped here while still borrowed
I don't have that much experience with Rust and I'm stuck here but in my opinion this doesn't seem like an impossible thing to do...
Edit: Improved example code so that only the iterator and not the whole collection is cloned thanks to the hint in Stargateur's answer