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) }),
};
}
I can't justify why only the commented line can't be compiled and thinks x1
's lifetime is not long enough. It seems c2
is equivalent to it, except the Box
is for the Wrap
struct directly. bt
just removes one layer of struct. I can't figure out what makes ContTrait
behave so differently.
Here's the error message when uncommenting the ContTrait
line:
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...