Trait impl and static lifetime from nowhere

Hi,

I have a trait Foo that I want to keep object-safe to use as a trait object. I'd like some generic helper methods which I'm defining using impl Foo (I saw that approach in some code, but could not find any documentation about impl Trait { } in the Rust book, would appreciate pointers).

Anyways, for some reason doing so adds a 'static lifetime to my self type. Can anyone explain what's happening? I think I can find a workaround using Rc/Arc, but I would love to avoid doing so.

Thank you!

Edit: also, if anyone has pointers explaining the logic behind 'static getting added to types in general, I'd appreciate it :slight_smile:

Trait in impl Triat { ... } is a trait object type. If we rewrite it using now preferable dyn syntax, we get

impl dyn Foo + 'static {
    pub fn do_it(&self) {
        self.do_something("Foo".into());
    }
}

That 'static is part of lifetime elision: trait objects always have a lifetime, but it is assumed to be 'static, unless the object is used as &'a T, where it is assumed to be 'a (not sure about this one). So, you probably want

impl<'a> dyn Foo + 'a {
    pub fn do_it(&self) {
        self.do_something("Foo".into());
    }
}
1 Like

Thanks a lot! That's exactly what I want :). Got a similar answer on IRC just now as well.

For the record, I couldn't find anything about this in the second edition of the book or in the reference after searching for one hour...!

It is in the reference: Lifetime elision - The Rust Reference

But yeah, this could be explained in the book as well.