3

I have below generic trait:

trait A<T> {
    fn foo(&self) -> T;
}

I have following struct which implements trait A for String and usize:

struct S;

impl A<String> for S {
    fn foo(&self) -> String {
        String::from("Hello world")
    }
}

impl A<usize> for S {
    fn foo(&self) -> usize {
        37
    }
}

When I call method foo, I can specify type to the variable and that works:

let value: usize = s.foo();

But how can I do the same thing with turbofish operator?

I tried following without success:

let text = s::<usize>.foo();
let text = s.foo::<usize>();
let text = s.::<usize>foo();

How do I use this operator instead of providing the type to the variable?

Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
  • What does the Rust reference documentation say about this operator? – Roland Illig Mar 12 '19 at 03:12
  • [How to call a method when a trait and struct use the same method name?](https://stackoverflow.com/questions/44445730/how-to-call-a-method-when-a-trait-and-struct-use-the-same-method-name) is also related. (The dupe applied to this question: `A::::foo(&s)`). – trent Mar 12 '19 at 04:07

1 Answers1

6

You cannot do this, because the "turbofish" operator is syntax for specifying generic parameters to something, but your method is not generic, even though it is defined in a generic trait, so there are no generic parameters to specify.

What you can do is to use the fully qualified syntax to explicitly name the trait, which is generic:

let text = A::<usize>::foo(&s);
Vladimir Matveev
  • 120,085
  • 34
  • 287
  • 296