如何Option从调用者的特定生命周期中提取引用并将其传回?
具体而言,我想借用参照Box<Foo>从Bar一个具有Option<Box<Foo>>在其中.我以为我能做到:
impl Bar {
fn borrow(&mut self) -> Result<&Box<Foo>, BarErr> {
match self.data {
Some(e) => Ok(&e),
None => Err(BarErr::Nope),
}
}
}
Run Code Online (Sandbox Code Playgroud)
......但结果是:
error: `e` does not live long enough
--> src/main.rs:17:28
|
17 | Some(e) => Ok(&e),
| ^ does not live long enough
18 | None => Err(BarErr::Nope),
19 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the …Run Code Online (Sandbox Code Playgroud) 这是我试图执行的代码:
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)));
}
Run Code Online (Sandbox Code Playgroud)
(在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
Run Code Online (Sandbox Code Playgroud)
我看到已经有很多关于借阅检查器问题的文档,但在阅读之后,我仍然无法弄清楚问题.
为什么这是一个错误,我该如何解决?
从&Result类型中提取数据的好方法是什么?
在我的具体情况下,我有一个&Result<DirEntry, Error>类型,我无法解开因为我没有拥有该对象.我尝试取消引用并克隆它(*left_item).clone(),但这只是给我一个错误的注释:
the method `clone` exists but the following trait bounds were not satisfied:
`std::result::Result<std::fs::DirEntry, std::io::Error> : std::clone::Clone`
Run Code Online (Sandbox Code Playgroud) 假设我有一个x类型为 的值Option<T>,如何将其转换为Option<&T>?
我尝试使用map:
let result = x.map(|x| &x)
^^ Error
Run Code Online (Sandbox Code Playgroud)
但我得到了错误:
cannot return reference to function parameter `x`
returns a reference to data owned by the current function
Run Code Online (Sandbox Code Playgroud)