type 别名

type-aliases.md
commit 23a7a7bdb6a6a43cd7efdd9176b1d3f75d9d0e70

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

  1. type Name = String;

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

  1. type Name = String;
  2. let x: Name = "Hello".to_string();

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

  1. let x: i32 = 5;
  2. let y: i64 = 5;
  3. if x == y {
  4. // ...
  5. }

这给出

  1. error: mismatched types:
  2. expected `i32`,
  3. found `i64`
  4. (expected i32,
  5. found i64) [E0308]
  6. if x == y {
  7. ^

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

  1. type Num = i32;
  2. let x: i32 = 5;
  3. let y: Num = 5;
  4. if x == y {
  5. // ...
  6. }

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

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

  1. use std::result;
  2. enum ConcreteError {
  3. Foo,
  4. Bar,
  5. }
  6. type Result<T> = result::Result<T, ConcreteError>;

这创建了一个特定版本的Result类型,它总是有一个ConcreteError作为Result<T, E>E那部分。这通常用于标准库中创建每个子部分的自定义错误。例如,io::Result