Rust实战技巧:消除歧义

原创
2017/01/30 01:21
阅读数 530

如果多个Trait有相同名称的关联类型(Associated Type),在使用时可能出现歧义:

trait Foo {
    type Bar;
}

trait Foo2 {
    type Bar;
}

trait Baz: Foo + Foo2 {
    fn bar() -> Self::Bar; // error: ambigous associated type `Bar` in bounds of `Self`
}

上面这段代码无法通过编译,因为Self::Bar可能是Foo的Bar也可能是Foo2的Bar,编译器无法判断。要消除这种类型的歧义,就要使用<Self as TYPE>::Bar语法了。

trait Baz: Foo + Foo2 {
    fn bar() -> <Self as Foo>::Bar; // ok!
}

通过这个语法指定具体类型,这个语法不常用。

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
1 收藏
0
分享
返回顶部
顶部