I have created this minimal example which encapsulates the crux I'm trying to wrap my head around.
use std::any::Any;
trait Trait {}
struct Struct {}
impl Trait for Struct {}
struct Container {
field: Option<Box<dyn Any>>,
}
impl Container {
fn set_field<T: Any>(&mut self, x: T) {
self.field = Some(Box::new(x));
}
}
fn main() {
let c = Container { field: None };
{
let mut s = Struct {};
setter(c, &mut s);
}
println!("no s anymore!");
}
fn setter(mut c: Container, t: &mut (dyn Trait + 'static)) {
c.set_field(t as *mut (dyn Trait));
}
This code only compiles if the setter method has the 'static life time bound for the t argument. But what I pass to this method above is a mutable reference to a struct, which has clearly a non-static lifetime. So why does this code even compile?
Thank you so much! What you're saying makes sense, but now my question boils down to why Struct is always 'static? I cannot find this to be specified anywhere, and even the opposite — I find only description of 'static as being the lifetime of the entire program (Lifetimes - The Rust Programming Language), which is clearly not the case for my struct s? (that's why I deliberately gave it an explicit scope in my example)
That's not a mutable reference anymore. It's a raw pointer, and Rust doesn't track lifetimes of raw pointers (so they satisfy the 'static requirement).