Sealed Traits
Tutorial Video
Text description (accessibility)
This video demonstrates the "Sealed Traits" functional Rust example. Difficulty level: Intermediate. Key concepts covered: Functional Programming. A public trait that external crates can implement is an extension point — any third party can add new implementations. Key difference from OCaml: 1. **Openness by default**: Rust traits are open by default (any crate can implement); OCaml's variant types are closed by default (new variants require source changes).
Tutorial
The Problem
A public trait that external crates can implement is an extension point — any third party can add new implementations. Sometimes that is undesirable: a trait for serialization formats should not be implementable outside the library, or a set of marker types should be closed for soundness. The sealed trait pattern prevents external implementations by requiring implementors to also implement a private "seal" trait that is inaccessible outside the crate.
🎯 Learning Outcomes
Sealed is used in std::io::Write internalsCode Example
#![allow(clippy::all)]
// Stub — awaiting conversion from OCaml source.Key Differences
[> A | B]) can be extended by external code, providing the opposite: open extension — similar to Rust's open traits.OCaml Approach
OCaml achieves closed type sets through module type signatures — a module with an opaque type t and a specific set of operations can only be extended within its defining module. More directly, OCaml's closed variant types (regular type t = A | B | C) prevent external extension by design — new variants cannot be added from outside the module. This is the idiomatic OCaml approach for closed sum types.
Full Source
#![allow(clippy::all)]
// Stub — awaiting conversion from OCaml source.Deep Comparison
OCaml vs Rust: Sealed Traits
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
Numeric trait that is implemented only for i32, f64, and u64 within your crate.Numeric on a type from another crate produces a compile error referencing the inaccessible Sealed supertrait.