Why does this code need a 'static bound on a type when all it uses is `const`?


#1

I’m trying to add an impl of a trait, Printable to an Option use a generic type bound - but the compiler complains that a `+ ‘static’ is needed for T, viz:-

impl<'a, T> Printable for Option<&'a T>
    where T: Printable
{
    const MyId: u64 = T::MyId;

    fn print(&self) {
        if let Some(printable) = *self {
            printable.print();
        }
    }
}

Adding where T: Printable + 'static makes this work. A slightly more complete example is on the Rust Playground. What I don’t understand is why. The associated constant, MyId, is const; it lives forever. Adding a static bound makes this impl next-to-useless, as I can’t then pass, say Option<&'a T> as a variable to a method; instead, I have to pass Option<&'static T>. I strongly suspect I don’t understand 'static' lifetimes properly. I certainly can’t get my head round the compiler’s error[E0311]: the parameter type T may not live long enough. How can a type not live long enough?

Many thanks if you try to explain this to me…


#2

I notice when you do add 'static, this warning looks significant:

warning: constant evaluation error: non-constant path in constant expression. This will become a HARD ERROR in the future, #[warn(const_err)] on by default
  --> <anon>:22:23
   |
22 |     const MyId: u64 = T::MyId;
   |                       ^^^^^^^

I think it’s related to this issue:


#3

Thank you. I’ve just come across that behavior you linked to. I can’t say for sure whether it’s related or not, but it certainly seems to be in the ballpark. Let’s hope associated constants get stablized quickly. They’re extremely useful an a great way to keep code logical. Associated statics would be nice too…