Sub topic 12
GATs with Type Parameters: Pointer Families
This chapter assumes you can write a trait with a plain associated type and read a lending iterator that uses a lifetime GAT. It also assumes you are comfortable with Rc, Box, and the Deref trait. Here the GAT takes a type parameter instead of a lifetime, which lets a trait describe a whole family of types.
The problem: abstracting over a type constructor
Rc and Box are not types by themselves. Rc<i32> and Box<String> are types. Rc and Box are type constructors: each takes a type and produces a new one.
Suppose you want one generic function or struct that works with either Rc or Box, and the caller chooses which. You might try a trait parameter, such as trait Wrap<P>. That fails, because P must be a complete type, and Rc on its own is not one. Before GATs, Rust had no direct way to pass a type constructor as a generic argument. Other languages call this feature higher-kinded types, and Rust still does not have it.
A GAT with a type parameter gives you a workaround. You write a marker type, called a family, that stands for the constructor. The trait's associated type is a function from T to the concrete type:
RcFamily::Pointer<T>isRc<T>.BoxFamily::Pointer<T>isBox<T>.
Generic code takes the family P as its parameter and writes P::Pointer<i32> wherever it needs a pointer.
Declaring the family
This is the full example from the plan. It compiles and prints 5 6.
use std::rc::Rc;
trait PointerFamily {
type Pointer<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 make<P: PointerFamily>(value: i32) -> P::Pointer<i32> {
P::new(value)
}
fn main() {
let a = make::<RcFamily>(5);
let b = make::<BoxFamily>(6);
println!("{} {}", *a, *b);
}Here is what each piece does:
type Pointer<T>;declares an associated type with its own type parameter. This is the only new syntax compared with a plain associated type.RcFamilyandBoxFamilyare empty structs. They hold no data. Their only job is to be a type that implements the trait, so they act as names for the two constructors.- In each
impl,type Pointer<T> = Rc<T>;fills in the function. TheTon the left is a fresh parameter, and the right side may use it. new<T>is a generic method whose return type,Self::Pointer<T>, depends on the method's ownT. The trait'sSelfpicks the pointer kind, and the caller picks the element type.make::<RcFamily>(5)returnsRc<i32>andmake::<BoxFamily>(6)returnsBox<i32>. The body ofmakenever mentions either type.
Adding bounds to the GAT
As written, Pointer<T> promises nothing. Generic code cannot even read the value, because the compiler knows only that P::Pointer<i32> is some type. You can put bounds on a GAT just as on a plain associated type, and the bounds may mention the GAT's own parameter:
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)
}
}
struct Pair<P: PointerFamily> {
left: P::Pointer<i32>,
right: P::Pointer<String>,
}
impl<P: PointerFamily> Pair<P> {
fn new(left: i32, right: &str) -> Self {
Pair {
left: P::new(left),
right: P::new(right.to_string()),
}
}
fn describe(&self) -> String {
format!("{} {}", *self.left, *self.right)
}
}
fn main() {
let shared = Pair::<RcFamily>::new(1, "shared");
let owned = Pair::<BoxFamily>::new(2, "owned");
println!("{}", shared.describe());
println!("{}", owned.describe());
}This prints 1 shared and 2 owned.
The bound Deref<Target = T> is checked once per implementation. Rc<T> and Box<T> both satisfy it for every T. Because of the bound, describe can write *self.left and get an i32, and *self.right and get a String. The struct holds two different pointees, i32 and String, through the same family. A single type parameter could not do that. A parameter Ptr would be either Rc<i32> or Rc<String>, never both.
Inference needs help
A GAT is not invertible. The compiler can go from RcFamily and i32 to Rc<i32>, but it cannot go back from Rc<i32> to RcFamily. Several families could produce the same concrete type. For example, RcFamily and a hypothetical CountedRcFamily could both set Pointer<T> = Rc<T>.
A function like this cannot infer P from its argument:
fn read<P: PointerFamily>(p: &P::Pointer<i32>) -> i32 {
**p
}Calling read(&some_rc) fails with a "type annotations needed" error. You must write read::<RcFamily>(&some_rc). That is why make::<RcFamily>(5) in the first example had to use a turbofish. Nothing in its arguments mentions P.
How this differs from lifetime GATs
The mechanism is the same as in the lending iterator, but the purpose is different.
| Aspect | Lifetime GAT | Type-parameter GAT |
|---|---|---|
| Example | `type Item<'a> where Self: 'a;` | `type Pointer<T>;` |
| What varies | How long a borrow lasts | Which element type is wrapped |
| Typical use | Lending iterators, borrowed views | Type families, container abstractions |
| Where clause | Usually needs `Self: 'a` | Often none |
| Inference | Lifetimes are inferred freely | The family is not inferred from the output |
A lifetime GAT usually needs where Self: 'a. The reason is that the method signature mentions &'a mut self, so the compiler must know that Self outlives 'a. A type-parameter GAT like Pointer<T> involves no borrow, so it needs no such clause. A where clause appears only when the GAT's definition or a method signature uses a reference with a lifetime. In that case, read the compiler's suggestion. It tells you which bound is missing.
Common mistakes
- Forgetting that
TisSizedby default. Every generic parameter, including a GAT's, must beSizedunless you writeT: ?Sized.BoxFamily::Pointer<str>is therefore rejected with the declaration above. To allow unsized pointees, declaretype Pointer<T: ?Sized>;. Thennewmust also acceptT: ?Sized, which a by-valuenewcannot, so you would need a separate constructor. - Assuming every pointer is
Clone.Rc<T>isClonefor anyT, butBox<T>isCloneonly whenT: Clone. A bound liketype Pointer<T>: Clone;cannot be satisfied byBoxFamily. You can writetype Pointer<T: Clone>: Clone;, which restricts every caller toClonepointees. - Mixing thread-safety up.
Rcis notSend. If your generic code spawns threads, add anArcFamilyand requireP::Pointer<T>: Sendat the use site. The bound on the trait itself would excludeRcFamily.
Limitations
Type families built from GATs are useful but narrower than real higher-kinded types.
- No dyn compatibility. A trait with a GAT is not dyn compatible, so
Box<dyn PointerFamily>is an error. Families are a compile-time idea and are resolved by monomorphization. They cannot be chosen at run time. - Marker types are required. You cannot write
Pair<Rc>. You must writePair<RcFamily>and declareRcFamilyyourself, which adds one small struct per constructor. - One-way inference. As shown above, the compiler infers
P::Pointer<T>fromPbut notPfromP::Pointer<T>. - Bounds on the GAT can restrict implementers. Every bound you add shrinks the set of types that can implement the trait. Keep the trait minimal and push extra requirements into where clauses on the functions that need them.
- Normalization can need hints. When a function has bounds like
P::Pointer<T>: Deref<Target = T>in addition to the trait's own bound, the compiler may report ambiguity. If you see this, repeat the bound explicitly in thewhereclause.
In practice, the main use of this pattern is library code that must support several smart pointers or storage strategies, such as persistent data structures that work with both Rc and Arc. For application code, a plain generic parameter such as Ptr: Deref<Target = i32> is simpler. Reach for a family only when one structure needs to apply the same pointer to several element types.
Exercise
Add an ArcFamily to the first PointerFamily example, where Pointer<T> is std::sync::Arc<T>. What are the two required changes, and does make::<ArcFamily>(7) need any change to make?
Show answer
Add use std::sync::Arc;, declare struct ArcFamily;, and write impl PointerFamily for ArcFamily { type Pointer<T> = Arc<T>; fn new<T>(value: T) -> Arc<T> { Arc::new(value) } }. The two changes are the new marker struct and its impl. make needs no change, because it works with any type that implements PointerFamily, so make::<ArcFamily>(7) returns an Arc<i32>.
Exercise
Why does fn read<P: PointerFamily>(p: &P::Pointer<i32>) -> i32 fail to infer P when called as read(&Rc::new(3)), and how do you fix the call?
Show answer
A GAT maps a family and a type to a concrete type, but it cannot be run backwards. Rc<i32> could be the output of several families, so the compiler cannot pick P from the argument. Name the family explicitly with a turbofish: read::<RcFamily>(&Rc::new(3)). (The function body also needs the Deref<Target = T> bound on Pointer<T> for **p to compile.)
Exercise
A teammate declares type Pointer<T>: Clone; on PointerFamily and then finds that BoxFamily no longer compiles. Why, and what are two ways to fix it?
Show answer
Box<T> implements Clone only when T: Clone. The bound requires Pointer<T>: Clone for every T, which Box<T> cannot satisfy. One fix is to remove the bound from the trait and write where P::Pointer<i32>: Clone on functions that need cloning. The other is to declare type Pointer<T: Clone>: Clone;, which limits all callers to Clone element types.