How to use function return value directly in Rust println

1.9k Views Asked by At

Rust allows formatted printing of variables this way:

fn main(){
  let r:f64 = rand::random();
  println!("{}",r);
}

But this doesn't work:

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

It shows up this error:

   |
31 |   println!("{}",rand::random());
   |                 ^^^^^^^^^^^^ cannot infer type for type parameter `T` declared on the function `random`

Is it possible to use function return value directly with println!?

2

There are 2 best solutions below

0
Aplet123 On BEST ANSWER

Rust doesn't know what type rand::random should be, so you can use the turbofish to provide a type hint:

println!("{}", rand::random::<f64>());
0
Michael Anderson On

The turbofish ::<f64> in println!("{}", rand::random::<f64>()); forces the generic part of rand::random to be f64. In this case the generic parameter matches up with the return type - but for other functions this need not be the case.

In such cases, it is possible to tell the compiler the return type of the function that you want, rather than the generic parameter. In that case, if you are using the nightly compiler you can use "type ascription".

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