更新时间:2022-11-24 14:48:46
如果编译器无法自行推断类型,则必须指定:
If the compiler cannot infer the type by itself, it must be specified:
let numbers: Vec<_> = (0..10).collect();
类型也不能从项目中省略.特别是,const
s 和 static
s 看起来很像 let
语句,但类型必须被指定:
Types also cannot be omitted from items. In particular, const
s and static
s look very much like let
statements, but the type must be specified:
const PI_SQUARED: i32 = 10;
// Not valid syntax
const HALF_PI = 1.5;
当类型为匿名时,不能指定
When the type is anonymous, it cannot be specified
fn displayable() -> impl std::fmt::Display {
""
}
fn main() {
let foo = displayable();
// Not valid syntax:
let foo: impl std::fmt::Display = displayable();
}
但大多数情况下,可以指定类型但不必指定:编译器可以从用法中推断出来.
But most of the time, the type can be specified but doesn't have to: The compiler can infer it from usage.
在 Rust 中,尽可能省略简单类型通常被认为是一种很好的做法.人们将决定某事不再简单并决定是否必须指定它的界限是非常基于意见的,超出了 *** 的范围.
In Rust, it is usually considered good practice to omit simple types when they can. The bound where people will decide that something is not simple anymore and decide that it must be specified or not is however very opinion-based and out of scope for ***.