skip to content

In Rust, how does a `Celsius(f64)` newtype stop a Fahrenheit reading reaching `set_target`, and what does the wrapper cost you?

level: middleimportance: should knowfreq 55%

answer

  1. a tuple struct with one field
  2. nominal, not structural, typing
  3. type alias versus new type
  4. no inherited methods or operators
  5. same size as f64 in practice

basics

~20 s

A tuple struct such as Celsius(f64) is a distinct type, so passing a Fahrenheit value where Celsius is expected fails with E0308, while a type alias compiles silently. The cost is code: no f64 methods or operators until you add them.

solid answer

~40 s

`struct Celsius(f64);` is a **tuple struct** with one field, and Rust structs are **nominal**: `Celsius` and `Fahrenheit(f64)` are different types even though both wrap an `f64`. So `t.set_target(Fahrenheit(70.0))` is E0308, "expected `Celsius`, found `Fahrenheit`", and the only way in is an explicit conversion such as `outdoor.to_celsius()`. A `type Celsius = f64;` alias gives no protection, because it is just another name for `f64`. At run time the wrapper costs nothing measurable here: `size_of::<Celsius>()` is 8. The cost is code: `Celsius` gets no `f64` methods or operators, so `Celsius(1.0) + Celsius(2.0)` is E0369 until you implement `Add`, and you derive the traits you need.

code

rust · 30 lines
rust
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
struct Celsius(f64);

#[derive(Debug, Clone, Copy)]
struct Fahrenheit(f64);

impl Fahrenheit {
    fn to_celsius(self) -> Celsius {
        Celsius((self.0 - 32.0) * 5.0 / 9.0)
    }
}

struct Thermostat {
    target: Celsius,
}

impl Thermostat {
    fn set_target(&mut self, target: Celsius) {
        self.target = target;
    }
}

fn main() {
    let mut t = Thermostat { target: Celsius(20.0) };
    let outdoor = Fahrenheit(70.0);
    t.set_target(outdoor.to_celsius());   // explicit conversion
    // t.set_target(outdoor);             // E0308: expected `Celsius`, found `Fahrenheit`
    let presets: Vec<Celsius> = [18.0, 21.0].into_iter().map(Celsius).collect();
    println!("{:?} {:?} {}", t.target, presets, std::mem::size_of::<Celsius>());
}

go deeper

for a junior

Know the three struct shapes, how to build each, and that .0 reads a tuple struct's field.

for a middle

Explain why a newtype gives E0308 where an alias compiles, and list what the wrapper does not inherit: methods, operators and traits.

for a senior

Weigh the boilerplate against the bugs it prevents, know repr(transparent) for layout guarantees, and use a newtype to add inherent methods to a foreign type.

for a principal

Decide where a codebase should wrap primitives, such as money, identifiers and physical units, and where the conversion noise outweighs the safety.

## Three struct shapes Rust has three kinds of struct, and the newtype is the second: | Shape | Declaration | Built as | Fields read as | |---|---|---|---| | named-field struct | `struct Thermostat { target: Celsius }` | `Thermostat { target: Celsius(20.0) }` | `t.target` | | tuple struct | `struct Celsius(f64);` | `Celsius(20.0)` | `c.0` | | unit-like struct | `struct Calibrated;` | `Calibrated` | none | The Reference adds two details. A tuple struct also defines a **constructor function** of the same name in the value namespace, so `Celsius` can be passed where a function is expected: `[18.0, 21.0].into_iter().map(Celsius)`. A unit-like struct implicitly defines a **constant** of its type with the same name, and the Reference guarantees a struct with no fields is zero-sized. ## Why a newtype catches the unit bug A **newtype** is a tuple struct with one field that wraps an existing type to give it a new meaning. The protection comes from **nominal typing**: two structs are different types because they have different names, regardless of what they contain. 1. `fn set_target(&mut self, target: Celsius)` accepts only `Celsius`. 2. `t.set_target(Fahrenheit(70.0))` fails with **E0308**, "mismatched types", "expected `Celsius`, found `Fahrenheit`". 3. The caller has to convert on purpose: `t.set_target(outdoor.to_celsius())`, where `to_celsius(self)` on the `Copy` type `Fahrenheit` returns `Celsius((self.0 - 32.0) * 5.0 / 9.0)`. Compare a **type alias**: `type Celsius = f64; type Fahrenheit = f64;` declares two new names for the same type. Passing a `Fahrenheit` to a function taking `Celsius` compiles without a warning, because both are `f64`. An alias documents intent; only a new type enforces it. ## What the wrapper costs **At run time, nothing measurable in this example.** `std::mem::size_of::<Celsius>()` prints 8, the size of an `f64`, and the wrapper adds no indirection. The default representation only guarantees what soundness needs, so code that depends on `Celsius` having exactly `f64`'s layout, for example across an FFI boundary, marks it `#[repr(transparent)]`; that guarantee is covered with type layout. **In code, a fair amount**, and this is the half interviewers probe: - No inherited methods. `Celsius` has none of `f64`'s methods; you call `c.0.abs()` or write the methods you want on `Celsius`. - No operators. `Celsius(1.0) + Celsius(2.0)` is **E0369**, "cannot add `Celsius` to `Celsius`", until you implement `Add` (covered with operator traits). - No traits. `Debug`, `Clone`, `Copy`, `PartialEq` and the rest must be derived or implemented; the derives themselves are covered with the standard traits. - Conversions are manual. Each boundary where a raw `f64` enters or leaves needs `Celsius(..)` or `.0`. Implementing `Deref<Target = f64>` to get the methods back is a tempting shortcut that the material on `Deref` treats as an anti-pattern. ## Getting values in and out - **In:** call the constructor, `Celsius(20.0)`, or a conversion method such as `Fahrenheit::to_celsius(self)`. A `From<f64>` impl is another option, covered with conversion traits. - **Out:** read the field, `c.0`, or destructure it, `let Celsius(v) = c;` (patterns are covered with destructuring). - **Receivers:** a small newtype that derives `Copy` can take `self` in its methods; the caller keeps its own copy, as `outdoor.to_celsius()` shows. Keeping these conversions at the edges of a program, where raw numbers arrive from sensors or files, lets everything in between work with the checked types. ## Other jobs a newtype does - **Inherent methods on a foreign type.** `impl String { .. }` in your crate is E0116, and rustc's own help suggests "a newtype wrapper like `struct MyType(ExternalType);`". A wrapper your crate owns can have any inherent methods. - **Implementing a foreign trait for a foreign type** uses the same wrapper; the rule that forces it is covered with trait coherence. - **Validated values.** A newtype whose field cannot be set from outside its module, built only through a checked constructor, carries an invariant; field privacy is covered with visibility. ## Choosing the shape - Use a **named-field struct** when fields have distinct roles that deserve names. - Use a **tuple struct** for a single wrapped value, or a short fixed group where position is obvious. - Use a **unit-like struct** for a type that carries no data, such as a marker or a type that only exists to implement a trait.

  • Why is `Celsius` usable as the argument to `.map(Celsius)`?
    Declaring a tuple struct also declares a constructor function of the same name, here a function from `f64` to `Celsius`. Any place that accepts a function or closure of that shape accepts the constructor, so `.map(Celsius)` wraps each `f64` without writing a closure.
  • Does the newtype make the program slower or bigger?
    Not here: `size_of::<Celsius>()` is 8, the same as `f64`, and the wrapper is resolved at compile time. If code relies on the exact layout, for example when passing it across FFI, mark it `#[repr(transparent)]`, which guarantees the layout of the inner field.
  • When would you choose a type alias over a newtype?
    When the goal is a shorter name for a long type, such as a nested generic, and you want every method and trait of the original type. An alias adds no checks at all, so it is the wrong tool whenever two quantities of the same representation must not mix.

  • type Celsius = f64 stops Fahrenheit values being passed
  • A newtype automatically gets the inner type's methods and operators
  • Wrapping f64 in a struct adds a heap allocation
  • Two tuple structs with the same field types are interchangeable
  • A unit-like struct takes one byte like any value