我正在尝试实现一个包含泛型方法的特征.
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正确的块?
E_n*_*ate 16
函数和方法中的类型参数是通用的.这意味着对于所有特征实现者,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
}
}
Run Code Online (Sandbox Code Playgroud)
另请阅读Rust编程语言的第2版:在特征定义中指定占位符类型及相关类型.
也可以看看:
除了使用关联类型的方法之外,从这个答案中,您还可以将泛型添加到特征中。
trait Trait<T> {
fn method(&self) -> T;
}
impl Trait<u8> for Struct {
fn method(&self) -> u8 {
16
}
}
Run Code Online (Sandbox Code Playgroud)
当只有一种特征的逻辑形式可供使用时,您可以使用“关联类型”方式。当有不止一种有意义的输出类型时,您可以使用通用特征,例如这是合法的:
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);
}
Run Code Online (Sandbox Code Playgroud)
据我所知,您无法使用基于关联类型的特征来执行此操作。
| 归档时间: |
|
| 查看次数: |
754 次 |
| 最近记录: |