How do I disambiguate associated types?

邮差的信 提交于 2020-01-14 09:17:30

问题


My current code looks like this:

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() {}

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?


回答1:


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

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

See also:

  • How to call a method when a trait and struct use the same method name?


来源:https://stackoverflow.com/questions/31251170/how-do-i-disambiguate-associated-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!