Sub topic 3
Generic Associated Type Syntax
Assume you know traits, generic bounds, borrowing, and the Iterator trait. Generic associated types (GATs) extend associated types with their own lifetime or type parameters.
The basic syntax
A GAT declaration places parameters after the associated type name:
trait LendingIterator {
type Item<'a>
where
Self: 'a;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}Item<'a> is a family of types. Each lifetime can produce a different concrete type. The method connects the returned item to the borrow of self.
A lending iterator
A lending iterator can return a reference that remains tied to the iterator's current mutable borrow:
trait LendingIterator {
type Item<'a>
where
Self: 'a;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}
struct WindowsMut<'t> {
data: &'t mut [i32],
position: usize,
}
impl<'t> LendingIterator for WindowsMut<'t> {
type Item<'a> = &'a mut [i32] where Self: 'a;
fn next<'a>(&'a mut self) -> Option<Self::Item<'a>> {
if self.position + 2 > self.data.len() {
return None;
}
let end = self.position + 2;
let window = &mut self.data[self.position..end];
self.position += 1;
Some(window)
}
}A plain associated type such as type Item = &mut [i32] cannot express that each result borrows from the particular call to next.
GATs with type parameters
GATs can also describe a family of types selected by a type parameter:
use std::rc::Rc;
trait PointerFamily {
type Pointer<T>;
fn new<T>(value: T) -> Self::Pointer<T>;
}
struct RcFamily;
impl PointerFamily for RcFamily {
type Pointer<T> = Rc<T>;
fn new<T>(value: T) -> Rc<T> {
Rc::new(value)
}
}
fn main() {
let value = RcFamily::new(5);
println!("{}", *value);
}Here, Pointer<T> is an abstraction over pointer types. Another implementation could choose Box<T>.
Limitations and trade-offs
GATs add expressive power but also increase complexity:
- Traits containing GATs are generally not usable as
dyn Traitobjects. - Borrow-checker errors involving GATs can be difficult to interpret.
- Higher-ranked lifetime bounds can sometimes imply stronger lifetime requirements than expected.
- Use a plain associated type when one fixed type per implementation is enough.
Exercise
What does Item<'a> represent in a lending iterator?
Show answer
It represents the item type produced for a particular lifetime 'a, usually tied to the borrow of the iterator during that call.