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.
pull/162/head
Ivan Tham 3 years ago committed by GitHub
parent c2321270fa
commit e6b427ce38
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -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.

Loading…
Cancel
Save