Type Erasure
Tutorial Video
Text description (accessibility)
This video demonstrates the "Type Erasure" functional Rust example. Difficulty level: Advanced. Key concepts covered: Functional Programming. Type erasure deliberately discards type information to enable heterogeneous collections, plugin systems, and dynamic dispatch. Key difference from OCaml: 1. **Explicit vs. implicit**: Rust requires explicit `Box<dyn Trait>` to erase types; Java erases generics silently at compile time (unsound without reification).
Tutorial
The Problem
Type erasure deliberately discards type information to enable heterogeneous collections, plugin systems, and dynamic dispatch. Storing values of different concrete types together requires erasing their specific types and retaining only a common interface. This is the mechanism behind Java's generics, Rust's Box<dyn Trait>, OCaml's existential types, and Go's interface values. The cost is one pointer indirection per method call; the benefit is open extension and runtime flexibility.
🎯 Learning Outcomes
Box<dyn Trait>, Arc<dyn Trait>, and Box<dyn Any>Any + downcast_ref provides safe type recovery after erasureCode Example
#![allow(clippy::all)]
// Stub — awaiting conversion from OCaml source.Key Differences
Box<dyn Trait> to erase types; Java erases generics silently at compile time (unsound without reification).downcast_ref::<T>() checks TypeId at runtime; OCaml's GADT pattern match handles this structurally without runtime type IDs.Box<dyn Any> exposes just downcast; OCaml's first-class modules expose whatever the module signature declares.Box<dyn Any> has unique ownership; Arc<dyn Any> enables shared ownership across threads; OCaml's GC handles all sharing automatically.OCaml Approach
OCaml erases types through:
type any = Any : 'a -> any packs any value with its type erased(module M : INTERFACE) erases the module identityObj.magic (unsafe, equivalent to Rust's transmute) — never use in productionOCaml's GC means erased values are always safely accessible; Rust's ownership system requires Box or Arc to heap-allocate erased values.
Full Source
#![allow(clippy::all)]
// Stub — awaiting conversion from OCaml source.Deep Comparison
OCaml vs Rust: Type Erasure
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
TypeMap that stores at most one value per type: insert<T: 'static>(&mut self, val: T) and get<T: 'static>(&self) -> Option<&T>.trait Plugin { fn name(&self) -> &str; fn run(&self); } and a registry that stores Vec<Box<dyn Plugin>>.fn erase_and_recover<T: Any>(val: T) -> Option<T> that boxes a value as Box<dyn Any> and then recovers it via downcast.