简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM