Skip to content

Commit e6b427c

Browse files
authored
Use a problem as the intro for newtype pattern (#153)
A problem can highlight some of the use cases of newtype pattern rather than discussing generally that rust is strongly typed. Make the user understand the need of newtype.
1 parent c232127 commit e6b427c

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

patterns/newtype.md

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
11
# Newtype
22

3-
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.
3+
What if in some cases we want a type to behave similar to another type or
4+
enforce some behaviour at compile time where using only type aliases would
5+
not be enough?
46

5-
A really convenient application of the Rust type system is the Newtype pattern.
7+
For example, if we want to create a custom `Display` implementation for `String`
8+
due to security considerations (e.g. passwords).
9+
10+
For such cases we could use the `Newtype` pattern to provide __type safety__ and __encapsulation__.
611

712
## Description
813

@@ -97,7 +102,7 @@ Here, `Bar` might be some public, generic type and `T1` and `T2` are some intern
97102

98103
## See also
99104

100-
- [Newtypes in the style guide](https://doc.rust-lang.org/1.0.0/style/features/types/newtype.html)
105+
- [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)
101106
- [Newtypes in Haskell](https://wiki.haskell.org/Newtype)
102107
- [Type aliases](https://doc.rust-lang.org/stable/book/ch19-04-advanced-types.html#creating-type-synonyms-with-type-aliases)
103108
- [derive_more](https://crates.io/crates/derive_more), a crate for deriving many builtin traits on newtypes.

0 commit comments

Comments
 (0)