Why does dereferencing avoid borrow in closure

Viewed 43

This code

fn broken(xs: &Vec<f32>) -> Vec<f32> {
    xs.iter()
        .flat_map(|x| xs.iter().map(|y| x - y))
        .collect()
}

gives me the error

error[E0373]: closure may outlive the current function, but it borrows `x`, which is owned by the current function

I understand why this is unsafe. However, I do not understand why writing *x fixes the issue. Does this force a copy?

fn working(xs: &Vec<f32>) -> Vec<f32> {
    xs.iter()
        .flat_map(|x| xs.iter().map(|y| *x - y))
        .collect()
}
0 Answers
Related