如何借用Option <t>中的内容?</t>

时间:2014-03-09 12:22:30

标签: rust

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

我有理由相信我在这里做的事情是有效的。

2 个答案:

答案 0 :(得分:15)

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

答案 1 :(得分: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)
        }
    }
}