Anonymous lifetime in trait impl

Hi all and thanks for your attention on my problem.
I have several structs S1, S2, ... with &S1, &S2, ... implementing IntoIterator<&str>. The implementation looks like (some code omitted to make it clear):

impl<'i> IntoIterator for &'i S1 {
    type Item = &'i str;
    type IntoIter = S1Iter<'i>;
    #[inline]
    fn into_iter(self) -> S1Iter<'i> { ... }
}

Now I have a trait that I want to automatically be implemented for all these structs. It has the following methods:

trait Trait {
    fn collect_to_vec(&self) -> Vec<&str>;
}

But now a problem occurs: I cannot write something like this:

impl<T> Trait for T where &T: IntoIterator<Item = &str> {
    ...
}

because the compiler would ask me to specify the lifetime of &T and &str.

I cannot write this, either:

impl<'i, T> Trait for T where &'i T: IntoIterator<Item = &'i str> {
    fn collect_to_vec(&self) -> Vec<&str> { ... }
}

or this:

impl<'i, T> Trait for T where &'i T: IntoIterator<Item = &'i str> {
    fn collect_to_vec(&'i self) -> Vec<&'i str> { ... }
}

because the where clause only guarantees IntoIterator implementation of a specific lifetime 'i, whereas the method implementation requires it to be applicable to all possible lifetimes.

You can see a reproducible version here in the playground.

How am I supposed to implement this? I suspect that I need to find a way to specify anonymous lifetime requirements in the where clause but I cannot find how.

The trick you need is a higher-ranked trait bound:

where for<'a> &'a T: IntoIterator<Item = &'a str>
2 Likes