Sub topic 13
Limitations and trade-offs of GATs
This chapter assumes you have read the earlier chapters on associated types, the lending iterator example, and the where Self: 'a clause. Generic associated types (GATs) have been stable since Rust 1.65. They solve real problems, but they cost something in flexibility and in error-message clarity. This chapter lists those costs so you can decide when a GAT is worth it.
Traits with GATs are not dyn compatible
A trait that contains a GAT cannot be used as a trait object. Writing Box<dyn LendingIterator> fails with error E0038, even if you name the lifetime. A trait object needs one fixed vtable. A GAT describes a family of types, one per lifetime or type argument, so the compiler cannot fix a single concrete type behind the pointer.
If you need dynamic dispatch, you can often drop the GAT and put the lifetime directly in a method signature. This only works when the item type is fixed, here &mut [T]:
trait LendingSlices<T> {
fn next_window(&mut self) -> Option<&mut [T]>;
}
struct WindowsMut<'t, T> {
slice: &'t mut [T],
start: usize,
size: usize,
}
impl<'t, T> LendingSlices<T> for WindowsMut<'t, T> {
fn next_window(&mut self) -> Option<&mut [T]> {
let end = self.start + self.size;
if end > self.slice.len() {
return None;
}
let window = &mut self.slice[self.start..end];
self.start += 1;
Some(window)
}
}
fn run(it: &mut dyn LendingSlices<i32>) {
while let Some(w) = it.next_window() {
w[1] += w[0];
}
}
fn main() {
let mut data = [1, 2, 3, 4];
let mut windows = WindowsMut { slice: &mut data, start: 0, size: 2 };
run(&mut windows);
println!("{:?}", data);
}This prints [1, 3, 6, 10]. You gain dyn support and lose generality. The trait now only describes slices, and it cannot express "any item type that borrows from me."
Lending iterators do not fit the existing tooling
Iterator is unchanged by GATs, so a lending iterator is a separate trait. That has three consequences:
forloops do not work with it. You writewhile let Some(x) = it.next().- The standard adapters (
map,filter,zip, and so on) are not available. You write your own, and their signatures need higher-ranked bounds. - You can hold only one item at a time. Each item borrows the iterator mutably, so calling
nextagain ends the previous item's life. You cannotcollectthe items.
Bounds on GATs are harder to write
The compiler requires where Self: 'a on most lifetime GATs, as you saw earlier. The bigger problem appears when you constrain a GAT in a generic function using a higher-ranked bound such as for<'a> I: LendingIterator<Item<'a> = &'a T>. In some cases the compiler then demands that I: 'static, which rejects types that borrow local data. The Rust 1.65 release notes list this among the known limitations. It makes generic code over lending iterators awkward, and some patterns cannot be written yet.
Type-parameter GATs are not full higher-kinded types
PointerFamily simulates a type constructor: you pass a marker type such as RcFamily and get Rc<T> for any T. Rust still has no way to write P<T> for a type constructor P directly. Every abstraction needs a marker struct and a trait, which adds boilerplate. Inference also works poorly through these projections, so you often need turbofish calls such as make::<RcFamily>(5).
Deciding whether to use one
| Situation | Choice |
|---|---|
| Items never borrow from the iterator | Plain `Iterator` |
| One concrete item type that borrows from `self`, and you need `dyn` | Method with an elided lifetime, as in `LendingSlices` |
| Generic item types that borrow from `self`, and no `dyn` | GAT with a lifetime parameter |
| Abstracting over `Rc` versus `Box` or similar | GAT with a type parameter |
Exercise
Why can you not write Box<dyn LendingIterator> for a trait that declares type Item<'a> where Self: 'a;, and what is one way to get dynamic dispatch anyway?
Show answer
A GAT stands for a different concrete type for every lifetime or type argument, so a trait object cannot fix a single type behind its vtable, and the trait is not dyn compatible (error E0038). One workaround is to drop the GAT and declare a method such as fn next_window(&mut self) -> Option<&mut [T]>, which ties the returned borrow to &mut self through lifetime elision. That trait is dyn compatible, but it supports only that one item type.