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); // 无效
}

类型别名在不用作关联类型时,必须包含一个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)。