diff --git a/patterns/newtype.html b/patterns/newtype.html index f5a115b..4fd6ea0 100644 --- a/patterns/newtype.html +++ b/patterns/newtype.html @@ -168,8 +168,12 @@

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.

-

A really convenient application of the Rust type system is the Newtype pattern.

+

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?

+

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

Use a tuple struct with a single field to make an opaque wrapper for a type. This creates a new type, rather than an alias to a type (type items).

@@ -241,7 +245,7 @@ most common uses, but they can be used for other reasons:

Here, Bar might be some public, generic type and T1 and T2 are some internal types. Users of our module shouldn't know that we implement Foo by using a Bar, but what we're really hiding here is the types T1 and T2, and how they are used with Bar.

See also