liveBook · Manning

Newtype idiom

As explained in Idiomatic Rust

The newtype pattern defines a distinct type, typically as a tuple struct containing an existing type, to add type information or behavior with minimal encapsulation.

A newtype wraps an existing value in a tuple struct to add meaning or type safety without much extra encapsulation. It suits data already represented adequately by a primitive, such as a `u32`. section 5.7

#[derive(Debug)]
struct BitCount(u32);
#[derive(Debug)]
struct ByteCount(u32);

These tuple structs give bit counts and byte counts distinct types, even though both contain a `u32`. section 5.7

Add methods to define safe conversions: `BitCount::to_bytes` divides by eight, while `ByteCount::to_bits` multiplies by eight. The tuple field remains directly accessible as `.0`, keeping the wrapper lightweight; use newtype when that simplicity is useful. section 5.7

impl BitCount {
    fn to_bytes(&self) -> ByteCount {
        ByteCount(self.0 / 8)    #1
    }
}

impl ByteCount {
    fn to_bits(&self) -> BitCount {
        BitCount(self.0 * 8)
    }
}

The conversion methods construct the destination wrapper around the converted value. section 5.7

How Idiomatic Rust covers it

How deep it goes
Defines tuple-struct wrappers and demonstrates conversion methods, stopping at simple examples.
Examples
Uses BitCount and ByteCount around u32 values, converting between them by factors of eight.
What you can do after
Build it from scratch by wrapping a primitive in tuple structs and adding conversion methods.
How it connects
Connects tuple structs with Rust's type system and type-safe conversions.

Also explained in

Compare how 4 books explain newtype idiom →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.