Keyword type[][src]

Expand description

为现有类型定义别名。

语法为 type Name = ExistingType;

Examples

type 不创建新类型:

type Meters = u32;
type Kilograms = u32;

let m: Meters = 3;
let k: Kilograms = 3;

assert_eq!(m, k);
Run

在 traits 中,type 用于声明 associated type:

trait Iterator {
    // 关联类型声明
    type Item;
    fn next(&mut self) -> Option<Self::Item>;
}

struct Once<T>(Option<T>);

impl<T> Iterator for Once<T> {
    // 关联类型定义
    type Item = T;
    fn next(&mut self) -> Option<Self::Item> {
        self.0.take()
    }
}
Run