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

5

我有一个名为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上的方法指定类型注释?

1个回答

4
我可以想到三种方法:
  • Command::<P>::help(self)
  • <Self as Command<P>>::help(self) (或者使用ListCommand代替Self
  • (self as &dyn Command<P>).help()(我不知道是否有一种不涉及dyn的变体。)

2
请注意,您可以将 () 替换为 P,其中 P 是任何东西... 还要注意,Command<P> 应该实际上是 Command,而 exec 应该是 exec<P>;然后问题就解决了。 - user2722968
编辑:将()替换为P。(由于对help的调用在impl<P>块中,因此根本不需要编写具体类型。) - Caesar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接