什么时候需要使用类型注解? [英] When do you need to use type annotations?

查看:61
本文介绍了什么时候需要使用类型注解?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读 Rust 的数据类型时书我注意到有时一个变量是用类型注释定义的,有时不是.

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];

推荐答案

必须指定类型

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

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 中,尽可能省略简单类型通常被认为是一种很好的做法.人们将决定某事不再简单并决定是否必须指定它的界限是非常基于意见的,超出了 StackOverflow 的范围.

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.

这篇关于什么时候需要使用类型注解?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆