使用构建器模式时,如何指定将超过构建器生存期的被引用对象的生存期?

时间:2019-12-23 21:28:44

标签: rust builder lifetime

以下代码演示了我正在尝试做的事情。

#[derive(Debug)]
struct Item {
    val: i32,
}

struct Builder<'a> {
    item: Option<&'a Item>,
}

impl<'a> Builder<'a> {
    fn new() -> Self {
        Self { item: None }
    }

    fn set_item(&mut self, item: &'a Item) -> &mut Self {
        self.item = Some(item);
        self
    }

    fn build(&mut self) -> &Item {
        self.item.unwrap()
    }
}

fn main() {
    let item = Item { val: 22 };
    let item_ref: &Item = Builder::new().set_item(&item).build();

    println!("{:?}", item_ref);
}

运行此命令会给我以下错误:

error[E0716]: temporary value dropped while borrowed
  --> src/main.rs:27:27
   |
27 |     let item_ref: &Item = Builder::new().set_item(&item).build();
   |                           ^^^^^^^^^^^^^^                        - temporary value is freed at the end of this statement
   |                           |
   |                           creates a temporary which is freed while still in use
28 | 
29 |     println!("{:?}", item_ref);
   |                      -------- borrow later used here
   |
   = note: consider using a `let` binding to create a longer lived value

我想我理解编译器为何会抱怨:由于对对象Item的引用的生存期仅与实际Builder一样长,但我似乎无法弄清楚指定Item引用应至少持续{em> 到Builder的时间,但是应该比它长寿的方式。

我可能会错误地考虑此问题,并且希望您能向我指出正确的方向!

0 个答案:

没有答案