Skip to content

Use a problem as the intro for newtype pattern #153

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jan 5, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions patterns/newtype.md
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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.
Expand Down