关联类型
学习目标
- 理解关联类型的用途
- 掌握关联类型 vs 泛型参数
- 实现带关联类型的 trait
核心概念
基本语法
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}
struct Counter {
count: u32,
max: u32,
}
impl Iterator for Counter {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
if self.count < self.max {
self.count += 1;
Some(self.count)
} else {
None
}
}
}
关联类型 vs 泛型
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}
trait Convert<T> {
fn convert(&self) -> T;
}
关联常量
trait Circle {
const PI: f64 = 3.14159265358979;
fn area(&self) -> f64;
}
默认关联类型
trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}
小结
| 概念 | 说明 |
|---|
type Item | 声明关联类型 |
Self::Item | 使用关联类型 |
| 每个 impl 唯一 | 关联类型只能指定一次 |