Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

类型别名

Syntax
TypeAlias
    type IDENTIFIER GenericParams? ( : Bounds )?
        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,并且不能包含 Bounds

类型别名在 trait 中作为关联类型使用时,不能包含 Type 规范,但可以包含 Bounds

类型别名在 trait impl 中作为关联类型使用时,必须包含 Type 规范,并且不能包含 Bounds

trait impl 中的类型别名的等号之前使用 where 子句(如 type TypeAlias<T> where T: Foo = Bar<T>)已弃用。等号之后的 where 子句(如 type TypeAlias<T> = Bar<T> where T: Foo)是首选。