繁体   English   中英

如何消除通用特征方法调用的歧义?

[英]How to disambiguate generic trait method call?

我有以下代码:

struct X { i: i32 }

trait MyTrait<T> {
    fn hello(&self);
}

impl MyTrait<i32> for X {
    fn hello(&self) { println!("I'm an i32") }
}

impl MyTrait<String> for X {
    fn hello(&self) { println!("I'm a String") }
}

fn main() {
    let f = X { i: 0 };
    f.hello();
}

这显然不会编译,因为编译器无法消除f.hello()属于哪个特征的歧义。 所以我得到了错误

error[E0282]: type annotations needed
  --> src\main.rs:17:7
   |
17 |     f.hello();
   |       ^^^^^ cannot infer type for type parameter `T` declared on the trait `MyTrait`

有什么方法可以注释hello的类型,以便我可以告诉编译器例如在f上调用MyTrait<String>::hello吗?

在深入研究之后,我偶然发现了 Rust 书中的“消除歧义的完全限定语法:调用具有相同名称的方法” 这种情况可以适应我的情况,可以使用f作为相应特征方法的接收者

<X as MyTrait<String>>::hello(&f);

这会按预期编译和工作。

甚至

<MyTrait<String>>::hello(&f);

作品。

您可以使用完全限定的 function 调用语法

fn main() {
    let f: X;

    // shorthand form
    MyTrait::<String>::hello(&f);

    // expanded form, with deduced type
    <_ as MyTrait<String>>::hello(&f);

    // expanded form, with explicit type
    <X as MyTrait<String>>::hello(&f);
}

在操场上奔跑

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM