别名
type
语句可以用来给现有类型起一个新名字。类型必须使用 UpperCamelCase
命名法,否则编译器会发出警告。此规则的例外是基本类型:usize
、f32
等。
// `NanoSecond`, `Inch`, and `U64` are new names for `u64`. type NanoSecond = u64; type Inch = u64; type U64 = u64; fn main() { // `NanoSecond` = `Inch` = `U64` = `u64`. let nanoseconds: NanoSecond = 5 as u64; let inches: Inch = 2 as U64; // 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); }
别名的主要用途是减少样板代码;例如,io::Result<T>
类型是 Result<T, io::Error>
类型的别名。