问题描述
以下代码无法在稳定的 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
成为具有默认值的关联类型,而只是 <Self::Bar as Trait>::Foo
主体内 OtherTrait
的方便别名。有什么办法可以做到这一点吗?
解决方法
有什么办法可以实现吗?
不完全是这样,但是您可以通过在 trait 之外定义一个普通的类型别名来获得类似的结果:
type OtherFoo<T> = <<T as OtherTrait>::Bar as Trait>::Foo;
trait OtherTrait {
type Bar: Trait;
fn example1() -> OtherFoo<Self>;
}
在您打算编写 Bla::MyFoo
或为泛型 <T as OtherTrait>::MyFoo
编写更长的 T
的地方,您可以分别编写 OtherFoo<Bla>
和 OtherFoo<T>
。如果你能克服它不在 OtherTrait
内的范围,它会很好地工作。