如何借用解包的Option< T&gt ;? [英] How to borrow an unwrapped Option<T>?

查看:102
本文介绍了如何借用解包的Option< T&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 .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));
    });
}

飞机包含实例我的 Position 结构:

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

m只是借用了位置信息而没有移动任何东西,但是借用检查器拒绝了我的代码:

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

我的错误在哪里?

推荐答案

您正在寻找 Option :: as_ref

You are looking for Option::as_ref:


Option< T> 转换为 Option<& T>

以下代码解决了您的问题:

The following code solves your problem:

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

对于可变版本, Option :: as_mut

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

您的代码不起作用,因为作为指出,您尝试将数据移出 Option 并借用移出的数据。

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<_,_>?

这篇关于如何借用解包的Option&lt; T&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆