Associated Type Bounds
Tutorial Video
Text description (accessibility)
This video demonstrates the "Associated Type Bounds" functional Rust example. Difficulty level: Advanced. Key concepts covered: Functional Programming. When a trait has associated types, callers often need to constrain those associated types — "give me an iterator whose items are `Clone`" or "give me a container whose element type implements `Display`." Before Rust 1.79, this required verbose `where Item: Clone` clauses in every bound. Key difference from OCaml: 1. **Syntax location**: Rust's associated type bounds are inline in the trait reference; OCaml's `with type` constraints are applied at the module signature level.
Tutorial
The Problem
When a trait has associated types, callers often need to constrain those associated types — "give me an iterator whose items are Clone" or "give me a container whose element type implements Display." Before Rust 1.79, this required verbose where Item: Clone clauses in every bound. Associated type bounds (Iterator<Item: Clone>) compress this into the bound itself, making complex generic signatures readable and reducing repetition in library code.
🎯 Learning Outcomes
Trait<AssocType: Bound> (stabilized in Rust 1.79)where clauses and understand when each form is clearestCode Example
#![allow(clippy::all)]
// Stub — awaiting conversion from OCaml source.Key Differences
with type constraints are applied at the module signature level.with type elaboration.OCaml Approach
OCaml's module system handles associated type constraints via module type constraints:
module type CONTAINER = sig
type t
type item
val items : t -> item list
end
module type DISPLAY_CONTAINER = CONTAINER with type item = string
The with type refinement is OCaml's mechanism for constraining associated types. Functors then take modules satisfying specific refined signatures. This is more verbose than Rust's inline bound syntax but is the standard OCaml pattern.
Full Source
#![allow(clippy::all)]
// Stub — awaiting conversion from OCaml source.Deep Comparison
OCaml vs Rust: Associated Type Bounds
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
fn find_max<C: Container<Item: Ord>>(c: C) -> Option<C::Item> using associated type bounds, returning the largest element.Mappable trait with type Item and fn map<B>(self, f: impl Fn(Self::Item) -> B) -> Self::Mapped<B> using GATs.fn collect_display<I: Iterator<Item: Display + Clone>>(it: I) -> Vec<String> and test it with vec!["a", "b"].into_iter().