主题
关联类型 Associated Types
关联类型允许在 trait 中声明占位符类型,具体实现时确定,简化了复杂的泛型语法。
基本示例
rust
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}
struct Counter {
count: u32,
}
impl Iterator for Counter {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
self.count += 1;
if self.count < 6 {
Some(self.count)
} else {
None
}
}
}
fn main() {
let mut counter = Counter { count: 0 };
while let Some(num) = counter.next() {
println!("计数器值: {}", num);
}
}