A newtype is a distinct type wrapper around an existing representation that preserves its runtime representation while enforcing compile-time type distinctions.
A newtype wraps an existing representation in a distinct compile-time type. It preserves the underlying value while preventing interchangeable domain values from being passed accidentally. section 5.2.2
Separate names with identical representations
Wrapping both identifiers as strings makes their roles explicit: ControllerName and ComponentIndex remain different to the developer and the compiler, even though each contains a String. section 5.2.2
Use the idiom when:
Several parameters share a representation but must not be confused. section 5.2.2
A domain-specific language needs safer identifiers than bare strings provide. section 5.2.2
Production code should trade a little wrapping for fewer copy-and-paste errors. section 5.2.2
How Functional Design and Architecture: Examples in Haskell covers it
How deep it goes
Defines the wrapper pattern and its compiler-visible distinction, but does not detail construction, unwrapping, or runtime mechanics.
Examples
Uses ControllerName and ComponentIndex as distinct wrappers around String.
What it assumes
Assumes familiarity with typed parameters and bare representations such as String.
What you can do after
Apply it by wrapping bare domain types so the compiler rejects interchangeable identifiers.
How it connects
Connects type safety with embedded domain-specific languages, algebraic data types, and functional programming.
Write Powerful Rust MacrosA newtype is a distinct wrapper type around an existing value that gives the value stronger type-level meaning and can enforce construction invariants.
Idiomatic RustThe newtype pattern defines a distinct type, typically as a tuple struct containing an existing type, to add type information or behavior with minimal encapsulation.
orphan ruleaddresses · Rust's orphan rule restricts trait implementations so that either the trait or the implementing type must be local to the defining crate.
type systemuses · A type system is a programming language’s set of rules and mechanisms for classifying values and expressions and constraining their valid uses and combinations.
type aliascontrasts with · A type alias is a declaration that gives an existing type an alternative name without creating a distinct type or representation.
tuple structuses · A tuple struct is a Rust struct whose unnamed fields are accessed by positional indices.
tupleuses · A tuple is a finite, ordered collection of elements treated as a single composite value or record.
structimplements · A struct is a composite data type or structure that groups related fields or values into a single unit.
This explainer was generated by Manning's knowledge graph from the text of Functional Design and Architecture: Examples in Haskell. The section links point to the parts of the book it draws on.