9

Having these rather contrived type definitions

trait Generic<T> {
    fn some(&self) -> T;
}

impl<T> Generic<T> for i32
where
    T: Default,
{
    fn some(&self) -> T {
        T::default()
    }
}

I would like to call some method explicitly specifying type T. Below code apparently does not work because the method itself is not generic.

fn main() {
    let int: i32 = 45;
    println!( "some: {}", int.some<bool>() );
}

What's the right way of calling some?

3
  • 1
    Compiler is not able to infer since println! macro accepts generic type. Here is some ideas : play.rust-lang.org/… Commented Dec 25, 2019 at 6:33
  • @ÖmerErden Great answer! But why is that &int.some() as &bool works while int.some() as bool does not? Commented Jan 1, 2020 at 9:02
  • You can't directly cast T into a target type, please see: doc.rust-lang.org/reference/expressions/… Commented Jan 1, 2020 at 11:05

1 Answer 1

7

You must specify the exact type, as you tried. Unfortunately, your function is not generic, and instead your implementation is generic, so you'd have to do the following:

fn main() {
    let int: i32 = 45;
    println!("some: {}", <i32 as Generic<bool>>::some(&int));
    // Or,
    println!("some: {}", Generic::<bool>::some(&int));
}

Alternatively you could define a helper trait:

trait HasSome {
    fn other_some<T>(&self) -> T where Self: Generic<T> {
        <Self as Generic<T>>::some(self)
    }
}
impl<T> HasSome for T {} // Blanket impl. 

Playground.


On a side note, please know that when specifying the generics of a type or function you need to use the "turbofish" ::<> operator:

let foo = Vec::<i32>::new(); // Vec<i32>
let foo = my_generic_function::<usize>(); // Calls my_generic_function with usize
let foo = Option::<usize>::None;
let foo = None::<usize>;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.