Lifetimes with `where` on a Trait

Hey

I have this:

struct Foo <'a, T: SomeTrait> {
 ....

}

So how do I design the impl block where in I have?

impl <'a, T> Foo <'a, T> 
where T: SomeTrait {  <---- how do i add a lifetime here?
...

Thanks

There are two ways. Using Serde as an example because it has a lifetime:

extern crate serde;
use serde::Deserialize;

struct Foo<T> {
    _t: T,
}

impl<'de, T> Foo<T> where T: Deserialize<'de> {
    // This impl applies to Foo<T> where T implements
    // Deserialize for *some* lifetime 'de.
}

impl<T> Foo<T> where T: for<'de> Deserialize<'de> {
    // This impl applies to Foo<T> where T implements
    // Deserialize for *all* lifetimes 'de.
}

Hey thanks :slight_smile:

I see the second one has "for all lifetimes 'de". Didn't really understand that. Can you give an example where that might be useful?

That didn't work. I need the lifetime for the member of the struct (_t in your case which is &'a SomeOtherStruct)

You probably want T: SomeTrait + 'a then, based on what I’m inferring you’re saying.

1 Like