多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
`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`类型的值是一样,在各种方面。 你也可以在泛型中使用类型别名: ~~~ use std::result; enum ConcreteError { Foo, Bar, } type Result<T> = result::Result<T, ConcreteError>; ~~~ 这创建了一个特定版本的`Result`类型,它总是有一个`ConcreteError`作为`Result`的`E`那部分。这通常用于标准库中创建每个子部分的自定义错误。例如,[`io::Result`](http://doc.rust-lang.org/nightly/std/io/type.Result.html)。