展开时无法移出共享引用后面的值

Cannot move out of value which is behind a shared reference when unwrapping

这是我要执行的代码:

fn my_fn(arg1: &Option<Box<i32>>) -> i32 {
    if arg1.is_none() {
        return 0;
    }
    let integer = arg1.unwrap();
    *integer
}

fn main() {
    let integer = 42;
    my_fn(&Some(Box::new(integer)));
}

(on the Rust playground)

我在以前的 Rust 版本中遇到以下错误:

error[E0507]: cannot move out of borrowed content
 --> src/main.rs:5:19
  |
5 |     let integer = arg1.unwrap();
  |                   ^^^^ cannot move out of borrowed content

在更现代的版本中:

error[E0507]: cannot move out of `*arg1` which is behind a shared reference
 --> src/main.rs:5:19
  |
5 |     let integer = arg1.unwrap();
  |                   ^^^^
  |                   |
  |                   move occurs because `*arg1` has type `std::option::Option<std::boxed::Box<i32>>`, which does not implement the `Copy` trait
  |                   help: consider borrowing the `Option`'s content: `arg1.as_ref()`

我看到已经有很多关于borrow checker问题的文档了,但是看了之后还是没搞清楚问题所在

为什么会出现这个错误,我该如何解决?

Option::unwrap()消耗选项,即按值接受选项。但是,您没有值,您只有对它的引用。这就是错误所在。

您的代码应该按照惯用的方式编写:

fn my_fn(arg1: &Option<Box<i32>>) -> i32 {
    match arg1 {
        Some(b) => **b,
        None => 0,
    }
}

fn main() {
    let integer = 42;
    my_fn(&Some(Box::new(integer)));
}

(on the Rust playground)

或者您可以使用 Option 组合器,例如 Option::as_ref or Option::as_mut paired with Option::map_or,正如 Shepmaster 所建议的:

fn my_fn(arg1: &Option<Box<i32>>) -> i32 {
    arg1.as_ref().map_or(0, |n| **n)
}

此代码利用了 i32 可自动复制的事实。如果 Box 中的类型不是 Copy,那么您根本无法按值获取内部值 - 您只能克隆它或 return 一个参考,例如,像这里:

fn my_fn2(arg1: &Option<Box<i32>>) -> &i32 {
    arg1.as_ref().map_or(&0, |n| n)
}

由于您只有对选项的不可变引用,因此您只能return对其内容的不可变引用。 Rust 足够聪明,可以将文字 0 提升为静态值,以便在没有输入值的情况下能够 return 它。

因为 Rust 1.40 有 Option::as_deref,所以现在你可以这样做:

fn my_fn(arg1: &Option<Box<i32>>) -> i32 {
    *arg1.as_deref().unwrap_or(&0)
}