struct Wrap<'a> {
pub data: Option<&'a i32>,
}
pub trait Boxable {
fn get_data(&self) -> Option<&i32>;
}
impl<'a> Boxable for Wrap<'a> {
fn get_data(&self) -> Option<&i32> {
self.data
}
}
struct ContTrait {
pub vbox: Box<Boxable>,
}
struct ContWrap<'a> {
pub vbox: Box<Wrap<'a>>,
}
fn main() {
let x1 = 15;
let bt = Box::new(Wrap { data: Some(&x1) });
// let mut c = ContTrait { vbox: Box::new(Wrap {data : Some(&x1)}) };
let mut c2 = ContWrap {
vbox: Box::new(Wrap { data: Some(&x1) }),
};
}
我无法证明为什么只有注释行无法编译并且认为x1
' 的生命周期不够长。它似乎c2
等同于它,除了直接Box
用于Wrap
结构。bt
只是删除了一层结构。我无法弄清楚是什么让ContTrait
行为如此不同。
这是取消注释该ContTrait
行时的错误消息:
error[E0597]: `x1` does not live long enough
--> src/main.rs:27:63
|
27 | let mut c = ContTrait { vbox: Box::new(Wrap {data : Some(&x1)}) };
| ^^ borrowed value does not live long enough
...
31 | }
| - borrowed value only lives until here
|
= note: borrowed value must be valid for the static lifetime...