API and Numeric Boundaries · 14 min · free with an account

Orphan Rules and Newtypes

Lesson preview · about 30%

A local wrapper creates a distinct type whose behaviour your crate can own.

Core idea

A newtype creates a distinct local type; an alias only gives an existing type another name.

Start with the idea

Rust’s coherence rules restrict trait implementations so that implementations can be selected consistently across crates. The orphan rules broadly require the trait or a relevant implementing type to be local, with additional rules for generic parameters and fundamental types. A type alias does not create a new local type for this purpose.

The example wraps Vec<u8> in a local Bytes type and implements the standard Display trait for that wrapper. It does not attempt to implement Display directly for Vec<u8>. The wrapper also creates an explicit API boundary: you can restrict construction, choose formatting and control which capabilities are exposed. Delegation is a design choice rather than an automatic consequence of wrapping.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 754 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Interview Prep