类型别名
语法
TypeAlias :
type
IDENTIFIER GenericParams? (:
TypeParamBounds )? WhereClause? (=
Type WhereClause?)?;
类型别名 为模块或代码块的类型命名空间中已存在的类型定义了一个新的名称。类型别名使用关键字 type
声明。每个值都有一个单一、特定的类型,但可以实现几种不同的 trait,并且可能与几种不同的类型约束兼容。
例如,以下代码将类型 Point
定义为类型 (u8, u8)
的同义词,即无符号 8 位整数对的类型
#![allow(unused)] fn main() { type Point = (u8, u8); let p: Point = (41, 68); }
元组结构体或单元结构体的类型别名不能用于限定该类型的构造器
#![allow(unused)] fn main() { struct MyStruct(u32); use MyStruct as UseAlias; type TypeAlias = MyStruct; let _ = UseAlias(5); // OK let _ = TypeAlias(5); // Doesn't work }
类型别名,当不作为关联类型使用时,必须包含一个 Type,并且不能包含 TypeParamBounds。
类型别名,当在 trait 中用作关联类型时,不能包含 Type 规范,但可以包含 TypeParamBounds。
类型别名,当在 trait impl 中用作关联类型时,必须包含 Type 规范,并且不能包含 TypeParamBounds。
在 trait impl 中的类型别名等号之前的 Where 子句(例如 type TypeAlias<T> where T: Foo = Bar<T>
)已被弃用。等号之后的 Where 子句(例如 type TypeAlias<T> = Bar<T> where T: Foo
)是首选的。