Sub topic 13
Limitations and trade-offs of GATs
What this chapter assumes
You have read the earlier chapters on this topic. You can write a trait with an associated type, and you have seen a generic associated type (GAT) with a lifetime parameter (the lending iterator) and with a type parameter (the pointer family). This chapter covers what GATs cannot do yet, what they cost, and when a simpler design is better. GATs have been stable since Rust 1.65, and the restrictions below describe stable Rust at that stage. Some may be relaxed in later releases, so check the release notes if a limit surprises you.
Where GATs stop
Traits with GATs are not dyn compatible
A trait with an ordinary associated type can be used as dyn Trait if you name the type, as in dyn Iterator<Item = u32>. A trait that has a GAT cannot be used as dyn Trait at all. The compiler must build one vtable (a table of method pointers) for the trait object. A GAT stands for a whole family of types, one for each lifetime or type argument, and a single vtable cannot describe an open-ended family.
This means Box<dyn LendingIterator> is not an option. You have three practical ways around it:
- Keep the code generic, with
fn process<L: LendingIterator>(l: L). This is the usual answer and it costs nothing at runtime, but it produces one copy of the function per type. - Write a second, dyn-compatible trait that covers only what the caller needs. Callback-based "internal iteration" is the common choice.
- Use an enum of the concrete types you support.
Here is option 2 for the windowing example from the lending iterator section. The trait hands each window to a closure instead of returning it, so no GAT is needed and the trait works as a trait object:
trait Windows {
fn for_each_window(&mut self, f: &mut dyn FnMut(&mut [i32]));
}
struct Sliding<'t> {
slice: &'t mut [i32],
size: usize,
}
impl<'t> Windows for Sliding<'t> {
fn for_each_window(&mut self, f: &mut dyn FnMut(&mut [i32])) {
let mut start = 0;
while start + self.size <= self.slice.len() {
f(&mut self.slice[start..start + self.size]);
start += 1;
}
}
}
fn run(source: &mut dyn Windows) {
source.for_each_window(&mut |w| w[1] += w[0]);
}
fn main() {
let mut data = [1, 2, 3, 4];
{
let mut s = Sliding { slice: &mut data, size: 2 };
run(&mut s);
}
println!("{:?}", data);
}The program prints [1, 3, 6, 10], the same result as the GAT version. The cost is control flow. The caller can no longer stop early with break, or pull items one at a time, unless you add a return value to the closure.
The required `where Self: 'a` clause
You met this clause in the earlier section on why GATs need where Self: 'a. The compiler requires it whenever the GAT has a lifetime parameter and a method uses that lifetime in a way that implies Self outlives it. The clause is not optional, and the compiler rejects the trait without it. The rule is deliberately conservative, because the compiler cannot yet tell when the bound is truly unnecessary.
Every implementor then carries the clause too. That restricts which types can implement the trait: a type that holds a short-lived borrow only satisfies Self: 'a for lifetimes 'a that its own borrow outlives. This is correct for lending iterators, but it can surprise you in designs where the GAT does not borrow from self.
Higher-ranked bounds can force `'static`
Sometimes you want to say "this holds for every lifetime", written for<'a>. A bound such as for<'a> I::Item<'a>: Debug ranges over all lifetimes 'a, including 'static. Because the GAT requires Self: 'a, the compiler can conclude that I must outlive 'static, and it reports that I does not live long enough. The same problem appears in equality bounds of the form for<'a> I: LendingIterator<Item<'a> = &'a str> in some positions.
When you hit this, try these in order:
- Add a helper trait with a blanket implementation, so the
for<'a>bound lives in one place. - Take a concrete type instead of a generic one at the call site.
- Pass a closure through
&mut dyn FnMutas in the example above, which sidesteps the bound.
This is a known gap in the compiler's handling of GATs. Treat error messages mentioning 'static in GAT code as a sign of this limit, not as a mistake in your lifetimes.
No `for` loops and no standard adapters
A for loop calls IntoIterator, and the standard Iterator trait has a plain type Item. A lending iterator is a different trait, so none of these work with it:
forloopsmap,filter,zipand the other adapterscollectandsum
You write while let Some(x) = it.next() by hand and define your own adapters. Writing an adapter such as map is harder than for Iterator, because the closure must accept Self::Item<'a> for every 'a. That is another place where higher-ranked bounds get in the way.
The standard Iterator also cannot be changed into a lending trait, because that would break every existing implementation. A lending iterator therefore lives in your crate or in a library such as streaming-iterator. It does not live in std.
Limits of type-parameter GATs
Bounds must hold for every argument
A bound written on a GAT must be satisfied for every type argument. This is useful when the bound really is universal. Requiring Deref<Target = T> works for both Rc and Box, and it lets generic code read through the pointer:
use std::ops::Deref;
use std::rc::Rc;
trait PointerFamily {
type Pointer<T>: Deref<Target = T>;
fn new<T>(value: T) -> Self::Pointer<T>;
}
struct RcFamily;
struct BoxFamily;
impl PointerFamily for RcFamily {
type Pointer<T> = Rc<T>;
fn new<T>(value: T) -> Rc<T> {
Rc::new(value)
}
}
impl PointerFamily for BoxFamily {
type Pointer<T> = Box<T>;
fn new<T>(value: T) -> Box<T> {
Box::new(value)
}
}
fn describe<P: PointerFamily>(number: i32, text: &str) -> String {
let n = P::new(number);
let s = P::new(text.to_string());
format!("{} {}", *n, *s)
}
fn main() {
println!("{}", describe::<RcFamily>(5, "hi"));
println!("{}", describe::<BoxFamily>(6, "yo"));
}The program prints 5 hi and 6 yo. A bound like type Pointer<T>: Clone would not work, though. Rc<T> is always Clone, but Box<T> is Clone only when T is. The BoxFamily implementation would be rejected, because its Pointer<T> must be Clone for every T. A family trait can only promise what all members share.
Inference needs help
A projection such as P::Pointer<i32> does not identify P, because different families could produce the same concrete type. The compiler therefore cannot infer P from a return type, and you write make::<RcFamily>(5) with the turbofish. This is true of all associated types, and it matters more with families, since the family is often the only generic argument.
Heavier signatures and slower builds
A GAT adds a parameter, a where clause, and often a lifetime to every function that touches it. Readers must follow Self::Item<'a> through each signature. Error messages involving projections of projections are long. This is a cost for every maintainer, so a GAT should earn its place.
Choosing between GATs and the alternatives
| Need | Option | Trade-off |
|---|---|---|
| Items borrow from the iterator itself | Lending iterator with a lifetime GAT | Not dyn compatible, no `for` loop, no std adapters |
| Same, but callers only need to visit each item | Callback (`for_each`-style method) | Dyn compatible, but no early pull-based control |
| Items can be copied or cloned cheaply | Plain `Iterator` returning owned values | Allocation or copying cost, but all adapters work |
| Items are positions in a buffer | Return indices and let the caller index | No GAT needed, but the borrow check protects less |
| Generic code over several pointer types | Type-parameter GAT (family trait) | Bounds must hold for all arguments, turbofish needed |
| Runtime choice among implementations | `dyn Trait` or an enum | A GAT-based trait cannot be used for this |
Summary of the limits
- A trait with a GAT cannot be made into a trait object.
- The
where Self: 'aclause is required and is stricter than some designs need. - Higher-ranked bounds on GAT projections can demand
'static. - Lending iterators work with neither
forloops nor the standard adapters. - Bounds on a type-parameter GAT must hold for every argument.
- Each GAT adds signature noise and longer error messages.
Exercise
You have a trait Source with type Item<'a> where Self: 'a;. A teammate wants to store a mix of different sources in a Vec<Box<dyn Source>>. Why does this fail, and what are two ways to change the design?
Show answer
A trait with a GAT is not dyn compatible, so dyn Source is not allowed. One fix is to add a second trait that has no GAT, for example one that passes each item to a &mut dyn FnMut(...) callback, and store Box<dyn ThatTrait>. Another fix is to put the sources in an enum with one variant per concrete type and match on it, or to keep the code generic over S: Source if the mix is not needed at runtime.
Exercise
In the PointerFamily trait, why would changing the declaration to type Pointer<T>: Clone; break the BoxFamily implementation?
Show answer
A bound on a GAT must hold for every type argument. Box<T> implements Clone only when T: Clone, so Box<T> is not Clone for all T, and the compiler rejects the implementation. Rc<T> would pass because it is Clone for every T.
Exercise
Why can you not write for window in windows_mut { ... } with the WindowsMut lending iterator from earlier in this tutorial, and what do you write instead?
Show answer
A for loop uses IntoIterator and Iterator, whose Item type is a plain associated type that cannot borrow from the iterator between calls. LendingIterator is a separate trait with a GAT, so for does not accept it. Use while let Some(w) = windows.next() { ... } instead.