What's the for<'a> TraitName<'a> Syntax?

I'm working on the bevy_hecs crate and I ran into this syntax I've never seen before here:

pub trait Query {
    #[doc(hidden)]
    type Fetch: for<'a> Fetch<'a>;
}

What's up with the for<'a> Fetch<'a>?

Fetch is a trait defined as:

trait Fetch<'a> {
    type Item;
    ...
    unsafe fn get(archetype: &'a Archetype, offset: usize) -> Option<Self>
    ...
}

So the lifetime, as I understand it, is used to tie a possible reference that could be set as the the Item in Fetch implementations so that it can contain a reference to the Archetype. For instance:

impl<'a, T: Component> Fetch<'a> for FetchRead<T> {
    type Item = &'a T;
    ...
    unsafe fn get(archetype: &'a Archetype, offset: usize) -> Option<Self> {
        ...
    }
    ...
}

So this makes sense to me, but I wanted to get a better understanding of that the weird for<'a> syntax was that somehow seems to eliminate the need for Query to be Query<'a>.

This might be a can of worms, but I think I might need to understand it. So, what dark magic have I uncovered? :face_with_raised_eyebrow:

It's part of a whole warehouse full of cans of worms.
HRTB to get you started. Many forum posts in the past on usage. for is just bad to search for, so not the easiest thing to find.

1 Like

It means that Query::Fetch must implement the following infinite list of traits:

  • Fetch<'a>
  • Fetch<'b>
  • Fetch<'c>
  • Fetch<'d>
  • Fetch<'e>

And so on for every possible lifetime.

3 Likes

Oh, OK, that's not as bad as I thought. I think that gets me as far as I need for my current understanding. Thanks to you both. :slight_smile:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.