Sub topic 1
Rust Associated Types and Generic Associated Types
Prerequisites
Assume you can define and implement Rust traits, write generic functions with trait bounds, and use basic borrowing and lifetimes. You should also know that Option<T> represents either Some value or None.
Quick recap: traits and generic bounds
A trait defines behavior that types can implement. A generic bound restricts a type parameter to types that provide that behavior.
fn show<T: std::fmt::Display>(value: T) {
println!("{value}");
}This function accepts any T that implements Display. The bound lets Rust verify that formatting is available.
Declaring and implementing an associated type
An associated type is a type chosen by each trait implementation. Declare it with type inside the trait.
trait Container {
type Item;
fn first(&self) -> Option<&Self::Item>;
}
struct Stack<T> {
items: Vec<T>,
}
impl<T> Container for Stack<T> {
type Item = T;
fn first(&self) -> Option<&Self::Item> {
self.items.first()
}
}
fn main() {
let stack = Stack { items: vec![10, 20, 30] };
println!("{:?}", stack.first());
}Stack<i32> chooses i32 as its Item. The implementation provides one associated Item type for each Stack<T> type.
Constraining associated types in bounds and where clauses
You can constrain an associated type in a trait bound. The syntax Trait<Name = Type> requires the associated type to equal a particular type.
fn sum_all<I>(iter: I) -> u32
where
I: Iterator<Item = u32>,
{
iter.sum()
}Here, I must implement Iterator, and its Item must be u32. A different iterator item type does not satisfy the bound.
Associated types you already use: Iterator and Add
Iterator declares type Item, so every iterator chooses what it yields. Add declares type Output, so an implementation chooses the result of addition.
Associated types make these relationships part of the trait contract instead of adding another freely selectable trait parameter.
Exercise
What does Iterator<Item = String> require?
Show answer
It requires the iterator to implement Iterator and to yield String values.