4

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?

3
  • What does the Rust reference documentation say about this operator? Commented Mar 12, 2019 at 3:12
  • 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::<usize>::foo(&s)). Commented Mar 12, 2019 at 4:07
  • turbofish operator is required only if a function does not take parameters which could indicate to compiler the type. So if there is no such parameter, then use turbofish, like: size_of::<u32>() is an example Commented Jan 5 at 0:31

1 Answer 1

10

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Perfection . Thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.