skip to content

Why does rustc reject `Temperature { kelvin: -5.0 }` outside its module, and how does that protect the type's invariant?

level: middleimportance: must knowfreq 62%

answer

  1. who may build the value
  2. one hidden field is enough
  3. E0451 on literals and patterns
  4. check first, then construct
  5. the module is the trust boundary

basics

~20 s

Because kelvin is a private field, rustc rejects any Temperature struct literal outside its module with E0451. Outside code must go through a constructor such as from_kelvin, which refuses negative values, so every Temperature it holds is valid.

solid answer

~40 s

A struct literal has to name every field, and naming a private field outside its module is E0451 ("field `kelvin` of struct `Temperature` is private"). The same check covers struct-update syntax `Temperature { ..t }` and patterns that bind the field; a tuple struct with a private field has a private constructor, so `temperature::Kelvin(3.0)` is E0603; and reading or assigning `t.kelvin` is E0616. The only routes to a `Temperature` from outside are therefore the module's own functions, and if `from_kelvin` returns `None` below zero, no outside code ever holds an invalid one. The boundary is the module, not the type: code in `temperature` or its child modules can still build a bad value, and a `pub enum` cannot hide its variants' fields, so put the validated struct inside the variant.

code

rust · 27 lines
rust
mod temperature {
    #[derive(Debug, Clone, Copy)]
    pub struct Temperature {
        kelvin: f64, // private: only this module can set it
    }

    impl Temperature {
        pub fn from_kelvin(kelvin: f64) -> Option<Temperature> {
            if kelvin >= 0.0 { Some(Temperature { kelvin }) } else { None }
        }
        pub fn from_celsius(c: f64) -> Option<Temperature> {
            Temperature::from_kelvin(c + 273.15)
        }
        pub fn kelvin(&self) -> f64 {
            self.kelvin
        }
    }
}

use temperature::Temperature;

fn main() {
    let body = Temperature::from_celsius(37.0).unwrap();
    println!("{:.2} K", body.kelvin()); // 310.15 K
    println!("{:?}", Temperature::from_kelvin(-5.0)); // None
    // let _bad = Temperature { kelvin: -5.0 }; // error[E0451]
}

go deeper

for a junior

Know that a struct with any private field cannot be built with a literal outside its module, and that the fix is a public constructor function that checks its input.

for a middle

Explain every route the check covers, literals, ..base, binding patterns, tuple constructors and field writes, and quote E0451, E0603 and E0616 to show where each lands.

for a senior

Show that the boundary is the module: keep invariant-carrying types in small modules, avoid pub(crate) fields, and wrap enum payloads in validated private-field structs.

for a principal

Argue for the review rule: a type with an invariant gets private fields and a checked constructor, because rustc then proves no outside code skips the check, with no test needed.

## The invariant and where rustc enforces it An **invariant** is a property every value of a type must have. For `Temperature` it is "never below absolute zero", so `kelvin >= 0.0`. Rust lets you make that a guarantee instead of a hope, and the tool is plain field privacy: declare `pub struct Temperature { kelvin: f64 }` with the field left private, and give the module one checked way to build a value. Field privacy works like every other privacy rule in Rust: a private field is visible to the module that declares the struct and to that module's descendants. Outside that subtree, any expression or pattern that names `kelvin` is a privacy error. Because a struct literal must initialise **every** field, one hidden field is enough to make the literal impossible for outside code. ## Every route to a value is checked The check is not limited to the obvious literal. Each way of building or opening up a `Temperature` from outside the module hits it: | Route, written outside `temperature` | Result | |---|---| | `Temperature { kelvin: -5.0 }` | E0451 "field `kelvin` of struct `Temperature` is private" | | `Temperature { ..t }` (struct update from an existing value) | E0451 at the `..t` | | `let Temperature { kelvin } = t;` | E0451, the pattern names the field | | `let Temperature { .. } = t;` | compiles, no field is named | | `t.kelvin` read, or `t.kelvin = -1.0` | E0616 | | `temperature::Kelvin(3.0)` for `pub struct Kelvin(f64);` | E0603 "tuple struct constructor `Kelvin` is private" | For the tuple-struct case, rustc's note says it directly: a constructor is private if any of the fields is private. Imported through `use` and called by its bare name, the same call is reported as E0423 ("cannot initialize a tuple struct which contains private fields"). ## Writing the validating constructor With the field private, the module supplies the only doors in: 1. A constructor that **checks, then builds**: `pub fn from_kelvin(kelvin: f64) -> Option<Temperature>` returns `None` for a negative input and only then writes `Temperature { kelvin }`. Returning `Result` with an error type is the same idea with a reason attached. 2. Convenience constructors, such as `from_celsius`, that call the checked one rather than writing a literal themselves, so the rule lives in one place. 3. **Getters** like `pub fn kelvin(&self) -> f64` instead of a `pub` field. A public field would let anyone assign `t.kelvin = -1.0` after construction, which breaks the invariant as surely as a bad literal. 4. No `pub` setter that skips the check. If mutation is needed, a method that re-validates and returns `Result` keeps the guarantee. Once that is in place, the guarantee is a compile-time fact: nothing outside the module can produce or edit a `Temperature` except through code you wrote and checked. ## The boundary is the module, not the type Privacy trusts a **module subtree**, which has consequences: - Any function in `temperature`, or in a module nested inside it, can still write `Temperature { kelvin: -5.0 }`. Keep invariant-carrying types in small modules so the trusted code is short enough to audit. - An `impl Temperature` block placed in a sibling module is outside the subtree, so even its methods get E0616 on `self.kelvin`. Privacy follows where the struct is declared, not where the `impl` sits. - `pub(crate) kelvin: f64` widens the trusted zone to the entire crate, and every module in it can then build an invalid value. That is rarely what an invariant wants. ## Enums cannot hide their payloads The variants of a `pub enum`, and the fields inside each variant, are always public with the enum; writing `pub` on a variant or on a variant's field is rejected with E0449. So `pub enum Reading { Raw { kelvin: f64 } }` lets anyone write `Reading::Raw { kelvin: -40.0 }`. To keep the guarantee, put the validated type in the variant, `Reading::Valid(Temperature)`, so the enum is freely constructible but its payload is not. ## What this does not cover Field privacy decides who can build and touch a value. It does not, by itself, make adding a field later a compatible change for other crates (that is the job of API-evolution tools such as `#[non_exhaustive]`), and when `unsafe` code relies on the invariant for memory safety, the stakes and the rules change, which is covered with sound safe abstractions.

  • Does a private field stop code elsewhere in the same crate from building an invalid Temperature?
    Only outside the defining module and its descendants. Any function in `temperature`, or in a module nested inside it, can still write `Temperature { kelvin: -5.0 }`, while an `impl Temperature` block in a sibling module cannot even read `self.kelvin` (E0616). Marking the field `pub(crate)` widens the trusted zone to the whole crate, which is usually too wide for an invariant.
  • How can outside code match on a Temperature without the field being exposed?
    A pattern that names the private field is E0451 outside the module, but `Temperature { .. }` compiles because it names no field. For real matching, call a getter such as `kelvin()` and match on the returned `f64`, or add a method that returns a public enum describing the value. The field itself stays private, so nobody outside can construct or change it.
  • Why is a pub enum a poor place to keep an invariant?
    Every variant of a `pub enum`, and every field inside a variant, is public with the enum, and writing `pub` on either is rejected with E0449. Anyone can therefore write `Reading::Raw { kelvin: -40.0 }`. Put the validated type inside the variant instead, as in `Reading::Valid(Temperature)`, so the enum is freely constructible but its payload is not.

A bank vault opened only by staff of the branch: customers deposit through the teller, who checks every note, but anyone working in the branch, back offices included, can still open the vault directly, so you keep the branch small.

  • A private field only hides reads; outside code can still build the struct with a literal.
  • Struct-update syntax ..existing lets outside code copy private fields into a new value.
  • Privacy is per type, so an impl block in any module can read the private field.
  • Enum variant fields can be made private to protect the payload.
  • Once the fields are private, nothing anywhere in the crate can build an invalid value.