How to use function return value directly in Rust println

百般思念 提交于 2020-05-28 05:38:06

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/61945688/how-to-use-function-return-value-directly-in-rust-println

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!