通过例子学习Rust

5.4 别名

使用 type 关键字定义某个类型的别名。类型名称必须采用骆驼命名法(即所有单词首字母大写),否则编译器将警告。只有基础类型(uint f32等)例外。

// `NanoSecond` is a new name for `u64` type NanoSecond = u64; type Inch = u64; // Use an attribute to silence warning #[allow(non_camel_case_types)] type uint64_t = u64; // TODO ^ Try removing the attribute fn main() { // `NanoSecond` = `Inch` = `uint64_t` = `u64` let nanoseconds: NanoSecond = 5 as uint64_t; let inches: Inch = 2 as uint64_t; // Note that type aliases *don't* provide any extra type safety, because // aliases are *not* new types println!("{} nanoseconds + {} inches = {} unit?", nanoseconds, inches, nanoseconds + inches); }

类型别名的一个主要作用是得到更简短的名称。例如 IoResult<T>Result<T, IoError> 的别名。