Lifetimes and trait objects

Hey guys, having trouble understanding the difference between the following two struct declarations:

trait Test{

struct TestStruct1<'a>{
    trait_obj: &'a Test

struct TestStruct2<'a>{
    trait_obj: &'a (Test + 'a)

I understand that since traits may be implemented on references, that the first 'a constrains the lifetime of the reference, and the second 'a constrains the lifetime of the fat-pointer reference that makes up the trait object. What I don't understand is why the second constraint is needed at all. Isn't it already impossible to create a reference (first 'a) to a fat-pointer reference (second 'a, trait object) without the second reference living as long as the first?

Further: both of these structs successfully compile. Is there anything you can do with the second struct that you can't do with the first? Can anybody point me to an example where this syntax Trait + 'lifetime has a use?


As of RFC 599, those field declarations are the same (I believe). That RFC has some discussion of various scenarios/use cases of object bounds.

Ah I see... thanks @vitalyd. Just out of curiosity: how did you find this information? And #2: I think there should be a way to clean up some of the old stackoverflow questions that seem to be misleading me

EDIT: I take it back: it looks like @shepmaster is doing a good job of keeping these current, take rust - Explicit lifetime declarations in trait objects held by structs - Stack Overflow for example...he even mentions RFC 599 lol, my bad

1 Like

I didn't recall the exact RFC # but I recalled coming across it - a quick search put me right on it :slight_smile:. From what I've seen, trait object lifetime bounds typically make people stumble in the Box<Trait> case, where 'static is the default, and thus more restrictive.