What is the meaning of for<'a>

How am I supposed to understand it?

for<'a>

Thank you

1 Like

This means "for all lifetimes 'a". For example consider this:

fn foo<T>(var: T)
where
    for<'a> T: SomeTrait<'a>,
{
    ...
}

this means something like:

fn foo<T>(var: T)
where
    T: SomeTrait<'lifetime1>,
    T: SomeTrait<'lifetime2>,
    T: SomeTrait<'lifetime3>,
    T: SomeTrait<'lifetime4>,
    T: SomeTrait<'lifetime5>,
    T: SomeTrait<'lifetime5>,
    T: SomeTrait<'lifetime6>,
    T: SomeTrait<'lifetime7>,
    T: SomeTrait<'lifetime8>,
    ...
{
    ...
}

where the list is infinite, going through every possible lifetime.

2 Likes

Less formally, it's useful when you don't care what lifetime something has (it doesn't have to match anything else specific), and you need to invent one out of thin air.

It's mostly useful for callback functions. If you used Fn(&'a T) with 'a from some outside scope, it would require the argument come from this very specific outside scope. With for<'a> Fn(&'a T) you can call it with any temporary lifetime.

8 Likes

Thanks for the informal explanation. Really appreciate it.

1 Like

For reference, this use of for is called a "higher-rank trait bound", and the Rustonomicon has a chapter about it.

5 Likes

There is a whole section about it in the drop-down menu of the following documentation: