Lifetimes with `where` on a Trait


#1

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


#2

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.
}

#3

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?


#4

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


#5

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