# 关联类型 Associated Types

URL: https://caijiao.org/rust/07-advanced/04-associated-types
Source: docs/rust/07-advanced/04-associated-types.md
Description: 关联类型是 Rust trait 中的一种抽象机制，通过在 trait 内定义类型占位符，简化泛型和实现，提高代码可读性和灵活性。

关联类型允许在 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);
    }
}
```

## 代码演示

Rust Playground 示例代码
