How to borrow an unwrapped Option<T>? [duplicate]

半城伤御伤魂 提交于 2019-12-25 01:26:45

问题


I want to iterate over a vector using .iter_mut() and .map():

fn calculate_distances(planes : &mut Vec<Aeroplane>, x: f64, y: f64) {
    fn calculate_distance(x1: &f64, y1: &f64, x2: &f64, y2: &f64) -> f6 { ... }
    planes.iter_mut().map(|a| if a.position.is_some() {
        let pos: &Position = &a.position.unwrap();
        a.distance = Some(calculate_distance(&x, &y, &pos.latitude, &pos.longitude));
    });
}

Aeroplane contains instance of my Position struct:

struct Position {
    latitude: f64,
    longitude: f64,
}

In my understanding I'm just borrowing the position information not moving out anything, but the borrow-checker refuses my code:

error[E0507]: cannot move out of borrowed content
   --> src/main.rs:145:31
    |
  4 |         let pos: &Position = &a.position.unwrap();
    |                               ^ cannot move out of borrowed content

Where is my mistake?


回答1:


You are looking for Option::as_ref:

Converts from Option<T> to Option<&T>.

The following code solves your problem:

let pos = a.position.as_ref().unwrap();

For a mutable version, Option::as_mut is provided.

Your code does not work, because as stated by turbulencetoo you try to move the data out of the Option and borrow the moved data.

However, in this case the better solution would be if let:

if let Some(ref pos) = a.position {
    a.distance = Some(calculate_distance(&x, &y, &pos.latitude, &pos.longitude));
}

See also:

  • How do I borrow a reference to what is inside an Option<T>?
  • How to unwrap a &Result<_,_>?


来源:https://stackoverflow.com/questions/51385381/how-to-borrow-an-unwrapped-optiont

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!