functionprintingrustreturnformatted-text

How to use function return value directly in Rust println


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!?


Solution

  • 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>());