Higher ranked trait bound in struct

So I'm trying to use some functionality from a crate that has higher ranked trait bounds, leaving only the important part it looks like this:

trait Trait<'a> { /* ... */ }

struct Interface<'a, Generic: for<'b> Trait<'b>> { /* ...*/ }

And I am trying to use it like this:

// This is my implementation
struct Struct<'a> { /* ... */ }

impl<'a> Trait<'a> for Struct<'a> { /* ... */ }

struct StructInWhichToStoreMyInteface<'a> {
    interface: Interface<'a, Struct<'a>>,

So my first question would be, why exactly this fails, since I can't wrap my head around what the lifetime bounds on the Interface are actually saying.

I tried moving the problem to the place where I use my struct by modifying it to look like this:

struct StructInWhichToStoreMyInteface<'a, T>
    T: for<'b> Trait<'b>,
    interface: Interface<'a, T>,

and it successfully removes the error, but now I cant even create this struct anymore, even when using 'static lifetimes:

static S: StructInWhichToStoreMyInteface::<'static, Struct<'static>>  = /* ... */;

So my second question would be, how can something with a static lifetime not be general enough to satisfy the lifetime bound?

Your original problem is coming from your implementation of Trait. for<'b> Trait<'b> says that Interface's Generic type parameter must implement Trait for every possible lifetime.

You have

impl<'a> Trait<'a> for Struct<'a> {
    /* ... */

which says that Struct implements Trait as long as the lifetime Struct contains is compatible with the lifetime Trait requires. That's not sufficient to meet Interface's requirements.

This works

impl<'a, 'b> Trait<'a> for Struct<'b> {
    /* ... */

because now we implement Trait for a separate lifetime parameter that isn't constrained by the lifetime in Struct. Generally speaking that means you won't be able to do a whole lot with the lifetimes inside Struct in your implementation of Trait though.

Here's a playground that builds successfully

The PhantomDatas are just there to silence the errors about unused type parameters in the structs.

1 Like

Thank you for helping me understand the issue and for providing a fix :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.