问题
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