簡體   English   中英

如何使用泛型方法實現特征?

[英]How do I implement a trait with a generic method?

我正在嘗試實現一個包含通用方法的特征。

trait Trait {
    fn method<T>(&self) -> T;
}

struct Struct;

impl Trait for Struct {
    fn method(&self) -> u8 {
        return 16u8;
    }
}

我得到:

error[E0049]: method `method` has 0 type parameters but its trait declaration has 1 type parameter
 --> src/lib.rs:8:5
  |
2 |     fn method<T>(&self) -> T;
  |     ------------------------- expected 1 type parameter
...
8 |     fn method(&self) -> u8 {
  |     ^^^^^^^^^^^^^^^^^^^^^^ found 0 type parameters

我應該如何正確編寫impl塊?

函數和方法中的類型參數是通用的 這意味着對於所有 trait 實現者, Trait::method<T>必須為任何T實現,其約束與 trait 指示的約束完全相同(在這種情況下, T上的約束只是隱式的Sized )。

您指出的編譯器錯誤消息表明它仍然需要參數類型T 相反,您的Struct實現假設T = u8 ,這是不正確的。 類型參數由方法的調用者而不是實現者決定,因此T可能並不總是u8

如果您希望讓實現者選擇特定類型,則必須改為在關聯類型中具體化。

trait Trait {
    type Output;

    fn method(&self) -> Self::Output;
}

struct Struct;

impl Trait for Struct {
    type Output = u8;

    fn method(&self) -> u8 {
        16
    }
}

另請閱讀The Rust 編程語言在具有關聯類型的 trait 定義中指定占位符類型的這一部分。

也可以看看:

除了使用關聯類型的方法之外,從這個答案中,您還可以將泛型添加到特征中。

trait Trait<T> {
    fn method(&self) -> T;
}

impl Trait<u8> for Struct {
    fn method(&self) -> u8 {
        16
    }
}

當只有一種特征的邏輯形式可供使用時,您可以使用“關聯類型”方式。 當存在多個有意義的輸出類型時,您可以使用通用特征,例如這是合法的:

struct Struct;

trait Trait<T> {
    fn method(&self) -> T;
}

impl Trait<u8> for Struct {
    fn method(&self) -> u8 {
        16
    }
}

impl Trait<String> for Struct {
    fn method(&self) -> String {
        "hello".to_string()
    }
}

fn main() {
    let s = Struct;
    let a: u8 = s.method();
    let b: String = s.method();
    println!("a={}, b={}", a, b);
}

據我所知,你不能用基於關聯類型的特征來做到這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM