我有一个名为Command<P>
的特性,包含两个函数:
trait Client<P> {}
trait Command<P> {
fn help(&self) -> String;
fn exec(&self, client: &dyn Client<P>) -> String;
}
struct ListCommand {}
impl<P> Command<P> for ListCommand {
fn help(&self) -> String {
return "This is helptext".to_string();
}
fn exec(&self, client: &dyn Client<P>) -> String {
self.help()
}
}
fn main() {
println!("Hello!");
}
Rust 抱怨我不能在
exec()
中调用 self.help()
,并显示以下错误:error[E0282]: type annotations needed
--> src\main.rs:15:14
|
15 | self.help()
| ^^^^ cannot infer type for type parameter `P` declared on the trait `Command`
如何为调用Self
上的方法指定类型注释?
()
替换为P
,其中P
是任何东西... 还要注意,Command<P>
应该实际上是Command
,而exec
应该是exec<P>
;然后问题就解决了。 - user2722968()
替换为P
。(由于对help
的调用在impl<P>
块中,因此根本不需要编写具体类型。) - Caesar