问题
While reading Data Types from the Rust Book I noticed that sometimes a variable is defined with a type annotation and sometimes not.
When should I use type annotations?
let tup: (i32, f64, u8) = (500, 6.4, 1);
let tup = (500, 6.4, 1);
let months = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
let a: [i32; 5] = [1, 2, 3, 4, 5];
回答1:
When types have to be specified
If the compiler cannot infer the type by itself, it must be specified:
let numbers: Vec<_> = (0..10).collect();
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 types cannot be specified
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();
}
When the types can be specified, but do not have too
But most of the time, the type can be specified but doesn't have to: The compiler can infer it from usage.
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 StackOverflow.
来源:https://stackoverflow.com/questions/61950263/when-do-you-need-to-use-type-annotations