最佳答案
如何从 Option
中提取一个引用并将其传递给调用者的特定生命周期?
具体来说,我想从一个包含 Option<Box<Foo>>
的 Bar
中借用一个对 Box<Foo>
的引用。我以为我能做到:
impl Bar {
fn borrow(&mut self) -> Result<&Box<Foo>, BarErr> {
match self.data {
Some(e) => Ok(&e),
None => Err(BarErr::Nope),
}
}
}
但结果是:
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 anonymous lifetime #1 defined on the body at 15:54...
--> src/main.rs:15:55
|
15 | fn borrow(&mut self) -> Result<&Box<Foo>, BarErr> {
| _______________________________________________________^ starting here...
16 | | match self.data {
17 | | Some(e) => Ok(&e),
18 | | None => Err(BarErr::Nope),
19 | | }
20 | | }
| |_____^ ...ending here
error[E0507]: cannot move out of borrowed content
--> src/main.rs:16:15
|
16 | match self.data {
| ^^^^ cannot move out of borrowed content
17 | Some(e) => Ok(&e),
| - hint: to prevent move, use `ref e` or `ref mut e`
好吧。也许不是。它看起来有点像我想做的事情和 Option::as_ref
有关,就像我可以做的那样:
impl Bar {
fn borrow(&mut self) -> Result<&Box<Foo>, BarErr> {
match self.data {
Some(e) => Ok(self.data.as_ref()),
None => Err(BarErr::Nope),
}
}
}
但是,那也不管用。
完整的代码,我有麻烦:
#[derive(Debug)]
struct Foo;
#[derive(Debug)]
struct Bar {
data: Option<Box<Foo>>,
}
#[derive(Debug)]
enum BarErr {
Nope,
}
impl Bar {
fn borrow(&mut self) -> Result<&Box<Foo>, BarErr> {
match self.data {
Some(e) => Ok(&e),
None => Err(BarErr::Nope),
}
}
}
#[test]
fn test_create_indirect() {
let mut x = Bar { data: Some(Box::new(Foo)) };
let mut x2 = Bar { data: None };
{
let y = x.borrow();
println!("{:?}", y);
}
{
let z = x2.borrow();
println!("{:?}", z);
}
}
我有理由相信我所做的在这里是有效的。