diff --git a/patterns/newtype.md b/patterns/newtype.md index 1589a24..b71aa7e 100644 --- a/patterns/newtype.md +++ b/patterns/newtype.md @@ -1,8 +1,13 @@ # Newtype -Rust has strong static types. This can be very different than what you are used to if you are coming from a loosely-typed language. Don't worry, though. Once you get used to them, you'll find the types actually make your life easier. Why? Because you are making implicit assumptions explicit. +What if in some cases we want a type to behave similar to another type or +enforce some behaviour at compile time where using only type aliases would +not be enough? -A really convenient application of the Rust type system is the Newtype pattern. +For example, if we want to create a custom `Display` implementation for `String` +due to security considerations (e.g. passwords). + +For such cases we could use the `Newtype` pattern to provide __type safety__ and __encapsulation__. ## Description @@ -97,7 +102,7 @@ Here, `Bar` might be some public, generic type and `T1` and `T2` are some intern ## See also -- [Newtypes in the style guide](https://doc.rust-lang.org/1.0.0/style/features/types/newtype.html) +- [Advanced Types in the book](https://doc.rust-lang.org/book/ch19-04-advanced-types.html?highlight=newtype#using-the-newtype-pattern-for-type-safety-and-abstraction) - [Newtypes in Haskell](https://wiki.haskell.org/Newtype) - [Type aliases](https://doc.rust-lang.org/stable/book/ch19-04-advanced-types.html#creating-type-synonyms-with-type-aliases) - [derive_more](https://crates.io/crates/derive_more), a crate for deriving many builtin traits on newtypes.