type 别名

—— `type`别名

欢马劈雪     最近更新时间:2020-08-04 05:37:59

139

type-aliases.md
commit 63bb3e66ee559d7e02f877a05a6bc54c9a5ab0d5

type关键字让你定义另一个类型的别名:

type Name = String;

你可以像一个真正类型那样使用这个类型:

type Name = String;

let x: Name = "Hello".to_string();

然而要注意的是,这一个别名,完全不是一个新的类型。换句话说,因为Rust是强类型的,你可以预期两个不同类型的比较会失败:

let x: i32 = 5;
let y: i64 = 5;

if x == y {
   // ...
}

这给出

error: mismatched types:
 expected `i32`,
    found `i64`
(expected i32,
    found i64) [E0308]
     if x == y {
             ^

不过,如果我们有一个别名:

type Num = i32;

let x: i32 = 5;
let y: Num = 5;

if x == y {
   // ...
}

这会无错误的编译。从任何角度来说,Num类型的值与i32类型的值都是一样的。

你也可以在泛型中使用类型别名:

展开阅读全文