[英]How do I borrow a reference to what is inside an Option<T>?
如何从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);
}
}
我有理由确定我尝试做的事情在这里是有效的。
从 Rust 1.26 开始,匹配人体工程学允许您编写:
impl Bar {
fn borrow(&mut self) -> Result<&Box<Foo>, BarErr> {
match &self.data {
Some(e) => Ok(e),
None => Err(BarErr::Nope),
}
}
}
在此之前,您可以使用Option::as_ref
,您只需要更早使用它:
impl Bar {
fn borrow(&self) -> Result<&Box<Foo>, BarErr> {
self.data.as_ref().ok_or(BarErr::Nope)
}
}
有一个可变引用的配套方法: Option::as_mut
:
impl Bar {
fn borrow_mut(&mut self) -> Result<&mut Box<Foo>, BarErr> {
self.data.as_mut().ok_or(BarErr::Nope)
}
}
不过,我鼓励删除Box
包装器。
从 Rust 1.40 开始,你可以使用Option::as_deref
/ Option::as_deref_mut
:
impl Bar {
fn borrow(&self) -> Result<&Foo, BarErr> {
self.data.as_deref().ok_or(BarErr::Nope)
}
fn borrow_mut(&mut self) -> Result<&mut Foo, BarErr> {
self.data.as_deref_mut().ok_or(BarErr::Nope)
}
}
在此之前,我可能会使用map
impl Bar {
fn borrow(&self) -> Result<&Foo, BarErr> {
self.data.as_ref().map(|x| &**x).ok_or(BarErr::Nope)
}
fn borrow_mut(&mut self) -> Result<&mut Foo, BarErr> {
self.data.as_mut().map(|x| &mut **x).ok_or(BarErr::Nope)
}
}
使用匹配人体工程学版本,您可以进行内联映射:
impl Bar {
fn borrow(&mut self) -> Result<&Foo, BarErr> {
match &self.data {
Some(e) => Ok(&**e),
None => Err(BarErr::Nope),
}
}
fn borrow_mut(&mut self) -> Result<&mut Foo, BarErr> {
match &mut self.data {
Some(e) => Ok(&mut **e),
None => Err(BarErr::Nope),
}
}
}
也可以看看:
首先,你不需要&mut self
。
匹配时,应该匹配e
作为参考。 您正在尝试返回e
的引用,但它的生命周期仅适用于该 match 语句。
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)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.