Generic Associated Types (GATs) let you define associated types in traits that take generic parameters, enabling more flexible trait implementations like iterators with varying item types.
trait Buffer {
type Item<'a> where Self: 'a;
fn get(&self) -> Self::Item<'_>; // Uses the GAT
}
struct MyBuffer;
impl Buffer for MyBuffer {
type Item<'a> = &'a str;
fn get(&self) -> Self::Item<'_> { "hello" }
}
- Define the trait with an associated type that includes generic parameters (like lifetimes).
- Implement the trait by specifying the concrete type for the associated type, matching the generic signature.
- Use the associated type in method signatures by referencing it with the required generic arguments.