我可以在 trait 的定义中为一个类型设置别名,而编译器不会假设我正在定义一个具有默认值的关联类型吗?

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?

下面的代码不能在稳定的 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;
}

编译器抱怨“关联类型默认值不稳定”。但是,我不希望 MyFoo 成为具有默认值的关联类型,只是 OtherTrait 主体内 <Self::Bar as Trait>::Foo 的方便别名。有什么办法可以实现吗?

Is there any way to achieve this?

不完全是这样,但是你可以通过在特征之外定义一个普通的类型别名来获得类似的结果:

type OtherFoo<T> = <<T as OtherTrait>::Bar as Trait>::Foo;

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

在您打算写 Bla::MyFoo 的地方,或者为通用 T 写更长的 <T as OtherTrait>::MyFoo,您可以分别写 OtherFoo<Bla>OtherFoo<T>。如果你能克服它不在 OtherTrait.

范围内的问题,它会很好地工作