【问题标题】:How to disambiguate generic trait method call?如何消除泛型特征方法调用的歧义?
【发布时间】:2020-05-15 22:42:42
【问题描述】:

我有以下代码:

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&lt;String&gt;::hello

【问题讨论】:

标签: rust


【解决方案1】:

经过一番挖掘后,我遇到了"Fully Qualified Syntax for Disambiguation: Calling Methods with the Same Name" from the Rust Book。可以适配我的情况,可以使用f作为对应trait方法的receiver

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

这会按预期编译和工作。

甚至

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

有效。

【讨论】:

    【解决方案2】:

    你可以使用fully qualified function call syntax:

    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);
    }
    

    Run in Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 2019-04-04
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多