我正在尝试实现一个包含泛型方法的特征。
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::method<T>
实施T
,其具有与特征所指示的完全相同的约束(在这种情况下,对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
}
}
另请阅读Rust编程语言的这一部分:Specifying placeholder types in trait definitions with associated types。
也可以看看: