Search code examples
rusttraitstype-aliasassociated-types

Can I alias a type inside of a trait's definition, without the compiler assuming that I am defining an associated type with a default?


The code below doesn't compile on stable Rust 1.52:

trait Trait {
    type Foo;
}

trait OtherTrait {
    type Bar: Trait;
    type MyFoo = <Self::Bar as Trait>::Foo; // This is currently illegal...
    
    // ...but I want to be able to write this:
    fn example1() -> Self::MyFoo;

    /// Instead of having to write this:
    fn example2() -> <Self::Bar as Trait>::Foo;
}

The compiler complains that "associated type defaults are unstable". However, I don't want MyFoo to be an associated type with a default, only a convenient alias for <Self::Bar as Trait>::Foo inside the body of OtherTrait. Is there any way to achieve this?


Solution

  • Is there any way to achieve this?

    Not exactly that, but you can achieve similar result by defining an ordinary type alias outside the trait:

    type OtherFoo<T> = <<T as OtherTrait>::Bar as Trait>::Foo;
    
    trait OtherTrait {
        type Bar: Trait;
        fn example1() -> OtherFoo<Self>;
    }
    
    

    Where you intended to write Bla::MyFoo, or the longer <T as OtherTrait>::MyFoo for a generic T, you can write OtherFoo<Bla> and OtherFoo<T> respectively. It works nicely if you can get over it not being scoped inside OtherTrait.