gpt4 book ai didi

rust - 解包时无法移出共享引用背后的值

转载 作者:行者123 更新时间:2023-12-03 11:39:23 24 4
gpt4 key购买 nike

这是我要执行的代码:

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()`

我看到已经有很多关于借阅检查器问题的文档,但是在阅读之后,我仍然无法弄清问题所在。

为什么这是一个错误,我该如何解决?

最佳答案

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 Option::as_mut Option::map_or 配对),如Shepmaster建议的那样:
fn my_fn(arg1: &Option<Box<i32>>) -> i32 {
arg1.as_ref().map_or(0, |n| **n)
}

此代码使用了 i32可自动复制的事实。如果 Box内的类型不是 Copy,那么您将根本无法按值获取内部值-您将只能对其进行克隆或返回引用,例如,如下所示:
fn my_fn2(arg1: &Option<Box<i32>>) -> &i32 {
arg1.as_ref().map_or(&0, |n| n)
}

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

关于rust - 解包时无法移出共享引用背后的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63535789/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com