如何借用对Option内部的引用 ?

问题描述 投票:15回答:2

如何从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),
        }
    }
}

......但结果是:

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
2个回答
12
投票

首先,你不需要&mut self

匹配时,您应该匹配e作为参考。您正在尝试返回e的引用,但它的生命周期仅适用于该匹配语句。

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)
        }
    }
}

16
投票

你确实可以使用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)
    }
}

我可能会添加一个map来删除Box包装器:

impl Bar {
    fn borrow(&self) -> Result<&Foo, BarErr> {
        self.data.as_ref().ok_or(BarErr::Nope).map(|x| &**x)
    }

    fn borrow_mut(&mut self) -> Result<&mut Foo, BarErr> {
        self.data.as_mut().ok_or(BarErr::Nope).map(|x| &mut **x)
    }
}

也可以看看:


从Rust 1.26开始,匹配人体工程学可以让你写:

fn borrow(&mut self) -> Result<&Box<Foo>, BarErr> {
    match &self.data {
        Some(e) => Ok(e),
        None => Err(BarErr::Nope),
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.