-
Book Overview & Buying
-
Table Of Contents
Design Patterns and Best Practices in Rust
By :
The NewType pattern has a long history in statically-typed functional programming, particularly in Haskell, where the newtype keyword has been a language feature since the 1990s. The pattern also appears in ML, OCaml, and other languages with strong type systems. The core idea of wrapping existing types in distinct types for semantic clarity and type safety predates Rust. It is a response to the issue that values that are conceptually different, such as temperature and weight, have the same type representation in the code, for example, a float. From the compiler's perspective, they are the same, and that leads to bugs when these values are inadvertently mixed up.
What Rust brings to this well-established pattern is zero-cost abstraction: the wrapped type compiles to exactly the same representation as the underlying type, with no runtime overhead. In languages with garbage collection or boxing, creating wrapper types often incurs performance costs. Rust...