调用非泛型特征方法时的泛型类型参数

Pow*_*nda 5 traits rust

我有一个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!");
}
Run Code Online (Sandbox Code Playgroud)

Rust 抱怨我无法调用self.help()exec()出现以下错误:

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`
Run Code Online (Sandbox Code Playgroud)

操场

如何指定调用方法的类型注释Self

Cae*_*sar 4

我可以想到三种方法:

  • Command::<P>::help(self)
  • <Self as Command<P>>::help(self)(或ListCommand代替Self
  • (self as &dyn Command<P>).help()(我想知道是否有不涉及的变体dyn。)

  • 请注意,您可以将 `()` 替换为 `P`,无论 `P` 是什么...还要注意,`Command&lt;P&gt;` 实际上可能应该是 `Command`,而 `exec` 应该是 `exec&lt; P&gt;`; 那么问题就消失了。 (2认同)