3

Another question shows two ways that you can force the return type of rand::random inside another expression. These two ways are: using type ascription

println!("{}", rand::random(): f64);

or using the turbofish operator

println!("{}", rand::<f64>random() );

These are telling the compiler different things, which work out the same in this case, but not in general. The first is saying that the return type is f64 and letting the compiler deduce the type used for the type parameter from that, while the second is explicitly specifying the generic type parameter.

In this case, the difference is only minimal, but are there cases where

I) The compiler can not deduce the type without one of turbofish or type ascription, and

II) The type ascription form is considerably more concise than the turbofish form?

Michael Anderson
  • 70,661
  • 7
  • 134
  • 187

1 Answers1

3

If a function has multiple generic types, and all can be deduced from the inputs except the output type, then you still have to use _ for the decuded type parameters in the turbofish notation, but not with type ascription:

fn add_and_convert<T, U, V>(u: U, v: V) -> T
where U: Add<V>, T: From<<U as Add<V>>::Output> {
    T::from(u + v)
}

println!("{}", add_and_convert(1u8, 3u8): i32);
println!("{}", add_and_convert::<i32, _, _>(1u8, 3u8));
// println!("{}", add_and_convert::<i32>(1u8, 3u8)); // won't compile
Frxstrem
  • 38,761
  • 9
  • 79
  • 119