Dan D.
Dan D.

Reputation: 8557

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

Upvotes: 5

Views: 2306

Answers (2)

Michael Anderson
Michael Anderson

Reputation: 73450

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

Upvotes: 1

Aplet123
Aplet123

Reputation: 35482

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

Upvotes: 5

Related Questions