Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I provide type annotations inline when calling a non-generic function?

Tags:

rust

One way I know is to provide the type annotations in Rust is by declaring an intermediate variable so the compiler knows the return type:

use std::num::Int
let max_usize: usize = Int::max_value();
println!("Max usize: {}", max_usize);

But how can I provide the type annotation "inline"?

For example, I don't expect the following to work unmodified because there's no type annotation at all, but this is the kind of thing I'm after:

use std::num::Int
println!("Max usize: {}", Int::max_value());

I tried Int::max_value::<usize>(), which gives error: too many type parameters provided: expected at most 0 parameter(s), found 1 parameter(s) - and that makes sense because max_value() isn't generic.

In Scala I would write myFunction(someDog: Animal) instead of writing

val someAnimal: Animal = someDog
myFunction(someAnimal)

Is there equivalent syntax in Rust?

like image 461
Caspar Avatar asked Feb 02 '15 07:02

Caspar


1 Answers

Like so:

fn main() {
    use std::num::Int;
    println!("Max usize: {}", <usize as Int>::max_value());
}
like image 66
DK. Avatar answered Jan 02 '23 22:01

DK.