Lifetime does not appear in the trait input types

Consider the following type family:

trait Throttler {
    type Resource;

struct MyThrottler { }

struct Permit<'a> {
    t: &'a MyThrottler,

impl<'a> Throttler for MyThrottler {
    type Resource = Permit<'a>;

type AnyThrottler = Box<dyn for<'a> Throttler<Resource = Permit<'a>>>;

I want to express that implementers of Throttler can return a Permit<'a> with some lifetime, unknown at the time of declaration.

However, using MyThrottler as an AnyThrottler fails with:

let t: AnyThrottler = Box::new(MyThrottler {}) as AnyThrottler;
// Fails with: binding for associated type `Resource` references lifetime `'a`, which does not appear in the trait input types

I've been trying to come up with a workaround based on intermediate traits, but I always get stuck one place or the other. Is this something the type system can support at this time or is it a limitation?

Rust playground.

With your example as given, it's a deeper limitation.

This feels like a GAT situation (stablizing soon), but GATs in trait objects is not stabilizing.

However, you can emulate lifetime GATs. Though it is somewhat gnarly in this case.

Edit: Here's a more general type alias too.

1 Like

I see! Thanks @quinedot :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.