我如何借用对 Option<T> 中内容的引用? [英] How do I borrow a reference to what is inside an Option<T>?
问题描述
如何从 Option
中提取引用并将其与调用者的特定生命周期一起传回?
How do I pull a reference out of an Option
and pass it back with the specific lifespan of the caller?
具体来说,我想从具有 Option
的 Bar
借用对 Box
的引用代码>在里面.我以为我可以做到:
Specifically, I want to borrow a reference to a Box<Foo>
from a Bar
that has an Option<Box<Foo>>
in it. I thought I would be able to do:
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`
嗯,好的.也许不会.看起来我想做的事情与 <有关code>Option::as_ref,也许我可以这样做:
Hm, ok. Maybe not. It looks vaguely like what I want to do is related to Option::as_ref
, like maybe I could do:
impl Bar {
fn borrow(&mut self) -> Result<&Box<Foo>, BarErr> {
match self.data {
Some(e) => Ok(self.data.as_ref()),
None => Err(BarErr::Nope),
}
}
}
...但是,这也行不通.
...but, that doesn't work either.
我遇到问题的完整代码:
Full code I'm having trouble with:
#[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);
}
}
我有理由确定我尝试做的事情在这里是有效的.
I'm reasonably sure what I've trying to do is valid here.
推荐答案
首先,你不需要&mut self
.
匹配时,应该匹配e
作为参考.您正在尝试返回 e
的引用,但它的生命周期仅适用于该匹配语句.
When matching, you should match e
as a reference. You are trying to return a reference of e
, but the lifetime of it is only for that match statement.
enum BarErr {
Nope
}
struct Foo;
struct Bar {
data: Option<Box<Foo>>
}
impl Bar {
fn borrow(&self) -> Result<&Foo, BarErr> {
match self.data {
Some(ref x) => Ok(x),
None => Err(BarErr::Nope)
}
}
}
这篇关于我如何借用对 Option<T> 中内容的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!