skip to content

In Rust, why is adding a `pub` field to a library's all-public `Config` struct a major change, and how does `#[non_exhaustive]` avoid it?

level: middleimportance: should knowfreq 42%

answer

  1. struct literals in other crates
  2. every field must be named
  3. E0063 missing field
  4. E0639 blocks struct expressions downstream

basics

~20 s

Other crates can build an all-public struct with a literal or destructure it field by field; both break when a field is added. With #[non_exhaustive], other crates cannot use literals and must write .. in patterns, so new fields are minor.

solid answer

~40 s

A struct whose fields are all `pub` can be written as a literal in any crate, `Config { timeout_ms: None, max_redirects: 5 }`, and destructured without `..`. Add `pub retries: u32` and those literals fail with E0063 (missing field) and the patterns with E0027, so Cargo's SemVer guide calls it **major**; so is adding a *private* field to an all-public struct. Marking the struct `#[non_exhaustive]` when it is first published means other crates get E0639 for any struct expression, including `..Default::default()`, and E0638 unless patterns end in `..`. They build it through `Default`, `new` or a builder and still read and assign the public fields, so adding fields later is minor. A struct that already has a private field gets the same protection without the attribute.

code

rust · 15 lines
rust
// Downstream crate: `httpc::Config` is a #[non_exhaustive] struct
// with public fields and a Default impl.
use httpc::Config;

fn main() {
    // Config { timeout_ms: None, max_redirects: 5 }       // E0639
    // Config { max_redirects: 5, ..Default::default() }   // E0639 too
    let mut cfg = Config::default();
    cfg.timeout_ms = Some(2_000); // public fields stay writable
    let cfg = cfg.with_max_redirects(5);

    // let Config { timeout_ms, max_redirects } = cfg;     // E0638
    let Config { max_redirects, .. } = cfg.clone();
    println!("{:?} redirects={max_redirects}", cfg.timeout_ms);
}

go deeper

for a junior

Recall that a struct literal must name every field, so a new field breaks literals written in other crates.

for a middle

Explain the private-field rules and what #[non_exhaustive] forbids downstream: struct expressions including functional update, and patterns without the .. rest pattern.

for a senior

Show you would ship Default or a constructor with any non_exhaustive struct and know the tuple-struct index trap and E0639 versus E0638.

for a principal

Weigh private fields with accessors against non_exhaustive public fields for each public type, and settle it before 1.0 because both choices are hard to reverse.

## Two things other crates can do with an all-public struct When every field of a `pub struct` is `pub`, code in any crate can do two things that depend on the **exact field list**: 1. **Build it with a struct literal**: `Config { timeout_ms: None, max_redirects: 5 }`. Rust requires every field to be named (or filled from a base with `..base`). 2. **Destructure it exhaustively**: `let Config { timeout_ms, max_redirects } = cfg;` names every field and no `..`. Add `pub retries: u32` in the next release and both break. rustc reports `error[E0063]: missing field `retries` in initializer of `Config`` for the literal and `error[E0027]: pattern does not mention field `retries`` for the pattern. That is why Cargo's SemVer guide lists these as major. ## The rules Cargo's SemVer guide gives | Change to a public struct | Classification | |---|---| | Add a public field when no private field exists | **Major** | | Add a private field when all current fields are public | **Major** | | Add or remove private fields when at least one already exists | Minor | | Add `#[non_exhaustive]` to a struct with no private fields | **Major** | | Add `#[non_exhaustive]` to a struct that already has a private field | Not breaking | The private-field rows follow from **privacy**: a struct with even one private field cannot be built with a literal outside its module and cannot be destructured without `..`, so other crates never depended on its full field list. One exception: for a **tuple struct**, adding or removing a private field that shifts the index of a public field (`.0` becoming `.1`) is major. ## What `#[non_exhaustive]` does to a struct The Reference says the attribute has **no effect inside the defining crate**. Outside it: - **No struct expressions.** `Config { .. }` fails with `error[E0639]: cannot create non-exhaustive struct using struct expression`, and that includes functional update syntax: `Config { max_redirects: 5, ..Default::default() }` is rejected too. - **Patterns must use `..`.** `let Config { timeout_ms, max_redirects } = cfg;` fails with `error[E0638]: `..` required with struct marked as non-exhaustive`; `let Config { max_redirects, .. } = cfg;` compiles. - **Tuple and unit structs.** The implicit constructor function of `pub struct Id(pub u64)` and the constant of a unit struct become no more visible than `pub(crate)`, so `Id(5)` fails downstream. - **Field access is untouched.** Public fields can still be read and assigned: `let mut cfg = Config::default(); cfg.timeout_ms = Some(2_000);` compiles in any crate. So the library must offer a way to create the value: a `Default` impl, a `new` constructor, or a builder (how to shape constructors and builders belongs with the material on `Default` and constructors). ## Choosing between private fields and the attribute Both make field additions minor; they differ in what callers can touch. - **Private fields with accessor methods** keep invariants enforceable and leave the representation free to change. The Rust API Guidelines reserve public fields for passive, C-style data and suggest hiding fields behind methods otherwise. - **`#[non_exhaustive]` with public fields** suits plain option bags such as `Config`: callers set fields directly, the crate only promises the fields it has published so far. - Either way, the choice has to be made when the struct is first published. Adding `#[non_exhaustive]` to a struct that already has only public fields breaks every literal downstream, so it waits for a major release. ## Checklist before publishing a struct - **Will callers need to build it?** Then ship `Default`, `new` or a builder together with `#[non_exhaustive]`, or callers in other crates may have no way to create a value. - **Do its fields carry invariants?** Then make them private instead, and expose methods. - **Is it a tuple struct with public fields?** Remember the index rule: inserting a field before a public one renumbers it. - **Is it a unit struct that may later carry data?** `#[non_exhaustive]` makes its constant `pub(crate)`, so callers must get the value from a function. ## Applied to the HTTP-client release If `httpc::Config` was published in 1.0 with only public fields and no attribute, `pub retries: u32` needs 2.0.0, or must be delivered another way, such as a separate builder method that stores the setting in a new type. If `Config` has been `#[non_exhaustive]` (or has carried a private field) since 1.0, `retries` can ship in 1.5.0 with a value supplied by `Default`, and every caller that wrote `Config::default()` plus field assignments keeps compiling.

  • Why does `Config { max_redirects: 5, ..Default::default() }` fail in another crate when `Config` is `#[non_exhaustive]` and implements `Default`?
    Functional update syntax is still a struct expression, and the Reference forbids constructing a non-exhaustive struct with a struct expression outside its crate, including with functional update. rustc reports E0639. The caller writes `let mut c = Config::default();` and then assigns the public fields.
  • Is adding a private field to a public struct that already has one a breaking change?
    No, Cargo's SemVer guide calls it minor: other crates could never use a struct literal or an exhaustive pattern on it. The exception is a tuple struct where the change shifts the index of a public field, which is major because `.0` now names a different field.

  • Adding a public field is minor because existing fields are untouched.
  • Functional update with Default lets other crates build a non_exhaustive struct.
  • #[non_exhaustive] makes a struct's public fields read-only in other crates.
  • A struct with a private field still needs #[non_exhaustive] before fields are added.
  • Adding #[non_exhaustive] to an all-public struct is safe in a minor release.