Associated types in Rust are type placeholders defined within a trait that allow implementors to specify a concrete type for that placeholder.
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> {
if self.count < 5 {
self.count += 1;
Some(self.count)
} else {
None
}
}
}
In this example, Item is the associated type. The Counter implementation specifies that its Item is u32, allowing the next method to return Option<u32> without hardcoding the type in the trait definition.