以下代码演示了我正在尝试做的事情。
#[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
的时间,但是应该比它长寿的方式。
我可能会错误地考虑此问题,并且希望您能向我指出正确的方向!