PowerPanda
PowerPanda

Reputation: 759

Generic type parameters when calling non-generic trait methods

I have a trait Command<P> with two functions like this:

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 complains I can't call self.help() in exec() with the following error:

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`

Playground

How can I specify the type annotations for calling methods on Self?

Upvotes: 5

Views: 122

Answers (1)

Caesar
Caesar

Reputation: 8484

I can think of three ways:

  • Command::<P>::help(self)
  • <Self as Command<P>>::help(self) (or ListCommand instead of Self)
  • (self as &dyn Command<P>).help() (I wonder if there's a variation of this that doesn't involve dyn.)

Upvotes: 4

Related Questions