PEA*_*EAR 1 closures ownership rust
我想使用 .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));
});
}
Run Code Online (Sandbox Code Playgroud)
Aeroplane 包含我的实例 Position结构:
struct Position {
latitude: f64,
longitude: f64,
}
Run Code Online (Sandbox Code Playgroud)
根据我的理解,我只是借用了位置信息并没有移出任何东西,但是借用检查器拒绝了我的代码:
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));
});
}
Run Code Online (Sandbox Code Playgroud)
我的错误在哪里?
您正在寻找Option::as_ref:
转换
Option<T>为Option<&T>。
以下代码可以解决您的问题:
let pos = a.position.as_ref().unwrap();
Run Code Online (Sandbox Code Playgroud)
对于可变版本,Option::as_mut提供了。
您的代码不起作用,因为正如turbulencetoo 所述,您尝试将数据移出Option并借用移动的数据。
但是,在这种情况下,更好的解决方案是让:
if let Some(ref pos) = a.position {
a.distance = Some(calculate_distance(&x, &y, &pos.latitude, &pos.longitude));
}
Run Code Online (Sandbox Code Playgroud)
也可以看看:
| 归档时间: |
|
| 查看次数: |
1286 次 |
| 最近记录: |