簡體   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