如何使用泛型方法实现特征?

洗礼

我正在尝试实现包含通用方法的特征。

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正确编写块?

E_net4在这里

函数和方法中的类型参数是通用的这意味着对于所有特征实现者,Trait::method<T>必须对任何T具有与特征所指示的约束完全相同的约束(在这种情况下,on约束T仅是隐式Sized)实施。

您指示的编译器错误消息表明它仍在使用参数type 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
    }
}

另请阅读Rust编程语言的这一部分在特征定义中指定具有关联类型的占位符类型

也可以看看:

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章