Search code examples
rustassociated-types

Is it possible to combine bounds of nested associated types?


I work with several traits that have associated types:

trait Foo {
    type FooType;
}

trait Bar {
    type BarType;
}

trait Baz {
    type BazType;
}

I have a function where I need to bound those associated types. I can do it like this (Playground):

fn do_the_thing<T>(_: T)
where
    T: Foo,
    T::FooType: Bar,
    <T::FooType as Bar>::BarType: Baz,
    <<T::FooType as Bar>::BarType as Baz>::BazType: Clone,
{}

This works, but it's very verbose. One problem is that I need to use the <Type as Trait> syntax to disambiguate a few paths, although that shouldn't be necessary. This issue has already been reported here.

I wonder if it's possible to shorten the definition of the above function. I thought, maybe it's possible to combine all bounds into one:

fn do_the_thing<T>(_: T)
where
    T: Foo<FooType: Bar<BarType: Baz<BazType: Clone>>>,
{}

But this results in a syntax error:

error: expected one of `!`, `(`, `+`, `,`, `::`, `<`, or `>`, found `:`
  --> src/main.rs:16:19
   |
16 |     T: Foo<FooType: Bar<BarType: Baz<BazType: Clone>>>,
   |                   ^ expected one of 7 possible tokens here

Is there a way to compress the bounds somehow?


Solution

  • This is now possible with the unstable feature associated_type_bounds (tracking issue).

    #![feature(associated_type_bounds)]
    
    fn do_the_thing<T>(_: T)
    where
        T: Foo<FooType: Bar<BarType: Baz<BazType: Clone>>>,
    {}
    

    (Playground)