Given the following function:
fn some_function<K, F: Fn(K) -> K>(f: F, vs: Vec<K>) -> Vec<K> {
let mut index = 0;
let new_vec = vs.iter().map(|x| {
index += 1;
for _ in 1 .. index {
x = f(x); // <- error here: mismatched types expected reference `&K` found type parameter `K`
}
*x
}).collect();
new_vec
}
How can i make it work ?
>Solution :
This example doesn’t work because .iter() will not produce an iterator of owned variables, but references to elements of vs. You could patch your code by turning it into into_iter():
fn some_function<K>(f: impl Fn(K) -> K, vs: Vec<K>) -> Vec<K> {
let mut index = 0;
vs.into_iter()
.map(|mut x| {
index += 1;
for _ in 1..index { x = f(x); }
x
})
.collect()
}
But you don’t need to keep track of index:
fn some_function<K>(f: impl Fn(K) -> K, vs: Vec<K>) -> Vec<K> {
vs
.into_iter()
.enumerate()
.map(|(i, mut x)| {
for _ in 0..i { x = f(x); }
x
})
.collect()
}