kwonryul
kwonryul

Reputation: 553

What's the meaning of bounding a trait by its own generic lifetime (trait Bar<'a>: 'a)?

I've seen this kind of code in the official reference:

trait Bar<'a>: 'a { }

I haven't thought of this kind of case.

I intuitively interpret "lifetime bound" of a type as follows:

some_reference: &'a Some_Type = &instance_of_Some_Type;
T: 'a // T is borrowed by "instance_of_Some_Type"

What's the meaning of trait Bar<'a>: 'a { } — there's a method which uses a parameter borrowing the type?

Is it the same as this?

impl Bar<'a> for Another_Type
where
    Another_Type: 'a
{
}

I can't think of the usage of above implication, what is an example usage of this case? I'm having a hard time getting the meaning of "lifetime parameter of a trait".

Upvotes: 4

Views: 96

Answers (1)

Dan R
Dan R

Reputation: 1494

A lifetime bound on a trait is about references inside some type that implements that trait.

For example, a 'static lifetime bound on a trait means it can't be implemented by any structs that contain references that don't outlive 'static.

Let's take your example without the lifetime bound:

trait Bar<'a> { }

This is a parameterized trait based on a lifetime 'a, but there is no requirement that an implementation of this actually outlives 'a, so we could do something like:

struct HasRef<'b>(&'b i32);
impl Bar<'static> for HasRef<'_> { }

which says that any HasRef struct - even one with a very short lifetime - implements the Bar<'static> trait.

Writing instead

trait Bar<'a>: 'a { }

says that any type implementing Bar<'a> must live at least as long as 'a, which probably makes more sense.

(These bounds are important especially for trait objects (with type like dyn Trait), since only the trait itself can the compiler about the lifetime of references inside this trait object.)

Upvotes: 2

Related Questions