我可以在 trait 的定义中给一个类型加上别名,而不需要编译器假设我定义了一个带有默认值的关联类型吗?

问题描述

以下代码无法在稳定的 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 内的范围,它会很好地工作。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...