调用非泛型函数时如何提供内联类型注释? [英] How do I provide type annotations inline when calling a non-generic function?
问题描述
我知道的一种方法是在 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());
我尝试了 Int::max_value::<usize>()
,这给出了 错误:提供的类型参数太多:预计最多 0 个参数,找到 1 个参数(s)
- 这是有道理的,因为 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.
在 Scala 中我会写 myFunction(someDog: Animal)
而不是写
In Scala I would write myFunction(someDog: Animal)
instead of writing
val someAnimal: Animal = someDog
myFunction(someAnimal)
Rust 中是否有等效的语法?
Is there equivalent syntax in Rust?
推荐答案
像这样:
fn main() {
use std::num::Int;
println!("Max usize: {}", <usize as Int>::max_value());
}
这篇关于调用非泛型函数时如何提供内联类型注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!