如何消除关联类型的歧义? [英] How do I disambiguate associated types?

查看:99
本文介绍了如何消除关联类型的歧义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前的代码如下:

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.上面的代码无法编译为:

My goal is to be able to use RichHasA as a HasA. The above code fails to compile with:

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`

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

which makes sense. How can I disambiguate associated types?

推荐答案

您可以使用

You can use what is called Fully Qualified Syntax (FQS):

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

另请参阅:

这篇关于如何消除关联类型的歧义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆