rust - 如何消除关联类型的歧义?

标签 rust associated-types

我当前的代码如下所示:

pub trait A {}
pub trait HasA {
    type A: A;
    fn gimme_a() -> Self::A;
}

pub trait RichA: A {}
pub trait RichHasA: HasA {
    type A: RichA;
    fn gimme_a() -> Self::A;
    // ... more things go here ...
}

pub fn main() {}

我的目标是能够将 RichHasA 用作 HasA。上面的代码无法编译:

error[E0221]: ambiguous associated type `A` in bounds of `Self`
  --> src/main.rs:10:21
   |
3  |     type A: A;
   |     ---------- ambiguous `A` from `HasA`
...
9  |     type A: RichA;
   |     -------------- ambiguous `A` from `RichHasA`
10 |     fn gimme_a() -> Self::A;
   |                     ^^^^^^^ ambiguous associated type `A`

这是有道理的。如何消除关联类型的歧义?

最佳答案

你可以使用所谓的Fully Qualified Syntax (FQS):

fn gimme_a() -> <Self as HasA>::A;
fn gimme_a() -> <Self as RichHasA>::A;

另见:

关于rust - 如何消除关联类型的歧义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31251170/

相关文章:

rust - 是否有指定数字功能的任何特征?

haskell - 关联数据族和重叠实例

swift - 使用通用关联类型扩展协议(protocol)

rust - Drop 不能用于实现扩展特征的通用结构

reference - RefCell<X> 和 RefCell<&X> 上的 borrow_mut 之间的区别

Swift Generics ...检查与关联类型的协议(protocol)的一致性

swift - 在 Swift 中使用具有约束关联类型的协议(protocol)作为属性

rust - 尽管有适当的特征约束,特征相关的 const 在特征定义上下文中不可用

rust - 如何在 Rust 中实现观察者模式?

rust - 没有继承的不同事物的列表?