我想使用.iter_mut()
和.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
包含我的Position
结构的实例:
struct Position {
latitude: f64,
longitude: f64,
}
据我了解,我只是在借用位置信息,没有移走任何东西,但是借用检查器拒绝了我的代码:
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
我的错误在哪里?
答案 0 :(得分:1)
您正在寻找Option::as_ref
:
从
Option<T>
转换为Option<&T>
。
以下代码解决了您的问题:
let pos = a.position.as_ref().unwrap();
对于可变版本,提供了Option::as_mut
。
您的代码不起作用,因为在stated by turbulencetoo时,您尝试将数据移出Option
并借用移动的数据。
但是,在这种情况下,更好的解决方案是if let:
if let Some(ref pos) = a.position {
a.distance = Some(calculate_distance(&x, &y, &pos.latitude, &pos.longitude));
}
另请参阅: