且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么时候需要使用类型注解?

更新时间:2022-11-24 14:48:46

必须指定类型

如果编译器无法自行推断类型,则必须指定:

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();

类型也不能从项目中省略.特别是,consts 和 statics 看起来很像 let 语句,但类型必须被指定:

Types also cannot be omitted from items. In particular, consts and statics 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.

在 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 ***.