Generic Associated Types (GAT) Basics
Tutorial Video
Text description (accessibility)
This video demonstrates the "Generic Associated Types (GAT) Basics" functional Rust example. Difficulty level: Advanced. Key concepts covered: Functional Programming. Before Generic Associated Types (GATs, stable in Rust 1.65), it was impossible to write a trait whose associated types were themselves generic over a lifetime or type parameter. Key difference from OCaml: 1. **Stability**: Rust GATs became stable in 1.65 (2022); OCaml's parameterized module types have been stable since OCaml 1.0.
Tutorial
The Problem
Before Generic Associated Types (GATs, stable in Rust 1.65), it was impossible to write a trait whose associated types were themselves generic over a lifetime or type parameter. This blocked implementing traits like LendingIterator (where each call to next borrows from the iterator itself) or a generic Container trait with a map method that changes the element type. GATs fill this gap, enabling patterns previously impossible in stable Rust.
🎯 Learning Outcomes
type Mapped<U> and type Iter<'a> inside trait definitionsCode Example
#![allow(clippy::all)]
// Stub — awaiting conversion from OCaml source.Key Differences
type Item<'a>), enabling the lending iterator; OCaml has no lifetime concept.where Self: 'a is often required); OCaml's parameterized types have no such requirement.'a t); Rust requires the full type Item<'a> where Self: 'a declaration.OCaml Approach
OCaml's module system naturally handles GAT-like patterns through parameterized module types:
module type CONTAINER = sig
type 'a t
val map : ('a -> 'b) -> 'a t -> 'b t
end
The type parameter 'a on t provides what Rust calls a GAT. OCaml functors parameterized by such modules achieve full higher-kinded programming without the complexity of GATs — it is a native, well-established feature.
Full Source
#![allow(clippy::all)]
// Stub — awaiting conversion from OCaml source.Deep Comparison
OCaml vs Rust: Gat Basics
Overview
See the example.rs and example.ml files for detailed implementations.
Key Differences
| Aspect | OCaml | Rust |
|---|---|---|
| Type system | Hindley-Milner | Ownership + traits |
| Memory | GC | Zero-cost abstractions |
| Mutability | Explicit ref | mut keyword |
| Error handling | Option/Result | Result<T, E> |
See README.md for detailed comparison.
Exercises
LendingIterator for a struct StrChunks<'s> that borrows from its source string and yields &'s str slices.Mappable trait with type Output<U> and implement it for Vec<T>, Option<T>, and Result<T, E>.Stack trait with type Pushed<T> that returns a new stack type with an element pushed, enabling typestate-like operations.