我有一个特征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
--> srcmain.rs:15:14
|
15 | self.help()
| ^^^^ cannot infer type for type parameter `P` declared on the trait `Command`
游乐场
如何指定Self
上调用方法的类型注释?
我可以想出三种方法:
Command::<P>::help(self)
<Self as Command<P>>::help(self)
(或ListCommand
而非Self
((self as &dyn Command<P>).help()
(我想知道是否有不涉及dyn
的变体。(