match + RefCell = X的寿命不够长

时间:2016-07-05 21:56:20

标签: rust borrow-checker

我需要初始化一个项目(fn init(&mut self) -> Option<&Error>),如果没有错误就使用它。

pub fn add(&mut self, mut m: Box<Item>) {
    if let None = m.init() {
        self.items.push(m);
    }
}

这是有效的,除非我需要检查错误是否有任何:

pub fn add(&mut self, mut m: Box<Item>) {
    if let Some(e) = m.init() {
        //process error
    } else {
        self.items.push(m); //won't compile, m is borrowed
    }
}

公平。需要使用RefCell。但是,这个

pub fn add(&mut self, mut m: Box<Item>) {
    let rc = RefCell::new(m);

    if let Some(e) = rc.borrow_mut().init() {           
        //process error         
    } else {
        self.items.push(rc.borrow_mut())
    }
}

以奇怪的结尾

结束
error: `rc` does not live long enough
        if let Some(e) = rc.borrow_mut().init() {
                     ^~
note: reference must be valid for the destruction scope surrounding block at 75:60...
    pub fn add_module(&mut self, mut m: Box<RuntimeModule>) {
                                                        ^
note: ...but borrowed value is only valid for the block suffix following statement 0 at 76:30
        let rc = RefCell::new(m);

我几乎尝试了所有内容:普通框,Rc&#39; ed框,RefCell&#39; ed Rc&#39; ed RefCell 。试图让this answer适应我的情况。没用。

完整示例:

use std::cell::RefCell;
use std::error::Error;

trait Item {
    fn init(&mut self) -> Option<&Error>;
}

struct ItemImpl {}

impl Item for ItemImpl {
    fn init(&mut self) -> Option<&Error> {
        None
    }
}

//===========================================

struct Storage {
    items: Vec<Box<Item>>,
}

impl Storage {
    fn new() -> Storage {
        Storage{
            items: Vec::new(),
        }
    }

    fn add(&mut self, mut m: Box<Item>) {
        let rc = RefCell::new(m);

        if let Some(e) = rc.borrow_mut().init() {           
            //process error         
        } else {
            self.items.push(*rc.borrow_mut())
        }
    }
}

fn main() {
    let mut s = Storage::new();
    let mut i = Box::new(ItemImpl{});
    s.add(i);
}

Playground

UPD:正如所建议的,这是一个&#34;家庭&#34;像我这样的错误,很好地解释了here。但是我的案子更容易解决。

1 个答案:

答案 0 :(得分:3)

正如krdln建议的那样,解决这个问题的最简单方法是返回if块,从而确定借用范围:

fn add(&mut self, mut m: Box<Item>) {
    if let Some(e) = m.init() {
        //process error
        return;
    } 
    self.items.push(m);
}
相关问题