pub struct TestStruct;
trait TestTrait {
fn trait_method(&self) -> &'static str;
}
impl TestTrait for TestStruct {
fn trait_method(&self) -> &'static str {
"test"
}
}
impl dyn TestTrait {
fn dyn_method(&self) -> String {
format!("asd-{}", self.trait_method())
}
}
struct Container<'a> {
items: Vec<&'a dyn TestTrait>,
}
When compiling the below main function, there is no issue:
fn main() {
let test = TestStruct;
let list = vec![
&test as &dyn TestTrait,
&test as &dyn TestTrait,
&test as &dyn TestTrait,
];
let container = Container { items: list };
container.items.iter().for_each(|item| {
println!("{}", item.trait_method());
});
}
but when switching out the trait_method for a dyn impl method, suddenly there are compile errors. The following:
fn main() {
let test = TestStruct;
let list = vec![
&test as &dyn TestTrait,
&test as &dyn TestTrait,
&test as &dyn TestTrait,
];
let container = Container { items: list };
container.items.iter().for_each(|item| {
println!("{}", item.dyn_method());
});
}
yields error:
borrowed value does not live long enough
cast requires thattestis borrowed for'static
Why?