Associated type with lifetime

pub SomeTrait {
  type X;
}

impl SomeTrait for Foo {
  type X = FooA;
}

impl SomeTrait for Bar {
  type X = BarA:
}

Now, suppose we want to add a lifetime

pub SomeTrait {
  type X;
}

impl SomeTrait for Foo {
  type X = FooA<'a>;
}

impl SomeTrait for Bar {
  type X = BarA<'a>:
}

How do we get this to work? I want to be able to attach an lifetime to a type (due to the struct needing to have a ref inside it).

You've found a usecase for GATs (Generic Associated Types):

pub trait SomeTrait {
    type X<'a>;
}

impl SomeTrait for Foo {
    type X<'a> = FooA<'a>;
}

This way, one could say:

pub trait SomeTrait {
    type X<'a>;
    
    fn foo<'a>(&'a self) -> Self::X<'a>;
}

Especially useful in certain iterator cases, but also in other instances.

Currently GATs are in beta(nightly? Check the GAT blog post), but are set to be stabilized Sometime Soon™.

2 Likes

In case someone else runs into this issue and wants to stay on stable:

@OptimisticPeach is definitely right in the general case. @OptimisticPeach is also right given the above problem statement.

However, if it turns out your problem if a bit more restrictive, where the references you need to store is actually the object itself, it is possible to do:

impl SomeTrait for &'a Foo { ... }

note the &'a . This only works if the lifetime you want to capture also happens to be the lifetime of the impl-ed object -- but nice thing is that this works on Rust stable.

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.