I searched this forum, and found threads that talk about this issue. However, they are either String vs &str or borrowed a value inside a struct like this. That does not look like my case. My problem is I pass in a Vec as a parameter to a function. And it seems that because of calling iter() so the lifetime of borrowed V may be invalid after this function execution/ when the next iter() operation (I could be wrong because I may totally misunderstand it).
Below is the code I use. How to fix it? Thanks.
#[derive(Clone, Debug)]
struct V {
data: f64,
}
impl V {
fn subtract(self, other: V) -> V {
V {
data: self.data - other.data,
}
}
}
fn f(data: Vec<V>) -> impl Iterator<Item = f64> {
let max_value_opt: Option<&V> = data.iter().max_by(|x, y| x.data.total_cmp(&y.data));
let exps = data
.iter()
.map(|v| {
max_value_opt.iter().map(|max_value: &&V| {
let cloned: V = (**max_value).clone();
v.clone().subtract(cloned)
})
})
.flatten();
let total: f64 = exps.clone().into_iter().map(|v| v.data).sum::<f64>();
exps.clone().into_iter().map(|value| value.data / total)
}