小编bai*_*ist的帖子

如何使用通用方法实现特征?

我正在尝试实现一个包含泛型方法的特征.

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

struct Struct;

impl Trait for Struct {
    fn method(&self) -> u8 {
        return 16u8;
    }
}
Run Code Online (Sandbox Code Playgroud)

我明白了:

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
Run Code Online (Sandbox Code Playgroud)

我该怎么写impl正确的块?

rust

6
推荐指数
2
解决办法
754
查看次数

标签 统计

rust ×1