ruststatictraitslifetime

What does it mean when we let a trait inherits 'static?


Rust supports trait inheritance, as follows:

pub trait A {}
pub trait B: A {}

B: A means that if some type T implements B, it also needs to implement all the methods in A.

But today I see the following code:

trait Display: 'static {
    fn print(&self);
}

What does it mean? It doesn't seem to be trait inheritance.


Solution

  • Rust doesn't have inheritance.

    What it has is a way to define constraints. For example a trait may be constrained to only be implemented by types which implement another trait.

    In your case the constraint is a lifetime bound.

    To implement your Display trait, an object may contain references but in this case their lifetime must respect this constraint.

    Let's suppose you have this type:

    struct S<'a> {
        s: &'a str,
    }
    

    Then you can't implement the trait for any lifetime, but only 'static.

    impl Display for S<'static> {
        fn print(&self){}
    }
    
    fn main() {
        let s1 = "test";
        let a = S { s: s1 };
        a.print(); // compiles
    
        let s2 = "test".to_string();
        let a = S { s: &s2 };
        a.print(); // doesn't compile because s doesn't live long enough
    }