skip to content

API Evolution and SemVer

A crate's public API decides what counts as a breaking change, and #[non_exhaustive] and sealed traits leave room to grow. Interviewers ask which changes need a major version.

on this pageshow

questions

6

In a Rust HTTP-client library, is adding a `TooManyRedirects` variant to the public `Error` enum a minor release, and what does `#[non_exhaustive]` change?

level: middleimportance: should knowfreq 50%

answer

  1. who matches on your enum
  2. exhaustiveness checked in other crates
  3. E0004 in downstream match expressions
  4. wildcard arm required only outside the crate

basics

~20 s

Not on a plain public enum: downstream matches listing every variant fail with E0004, so a new variant is major. If the enum was #[non_exhaustive] from its first release, other crates must keep a wildcard arm, and new variants are minor.

solid answer

~40 s

For an ordinary `pub enum Error`, adding a variant is a **major** change under Cargo's SemVer guidelines: any other crate with an exhaustive `match` now fails with E0004 because the new variant is not covered. If the enum was declared `#[non_exhaustive]`, matching its variants in other crates does not count toward exhaustiveness, so those matches must already carry a `_` arm, and adding `TooManyRedirects` in 1.5.0 is a **minor** change. Inside the defining crate the attribute has no effect. Callers can still construct `Error::Connect(..)`; only a variant that is itself `#[non_exhaustive]` blocks construction. Two traps: adding the attribute later to an existing enum is itself major, and the `_` arm means callers no longer get a compile error telling them a new failure kind exists.

code

rust · 19 lines
rust
// Downstream crate: depends on the `httpc` library,
// whose `pub enum Error` is marked #[non_exhaustive].
use httpc::Error;

fn describe(e: &Error) -> String {
    match e {
        Error::Timeout => "request timed out".to_string(),
        Error::Connect(host) => format!("could not connect to {host}"),
        // Required outside the defining crate: covers variants
        // added in later minor releases.
        _ => "other HTTP client error".to_string(),
    }
}

fn main() {
    // Variants of a #[non_exhaustive] enum can still be constructed.
    let e = Error::Connect("example.com".to_string());
    println!("{}", describe(&e));
}

go deeper

for a junior

Recall that a Rust match must cover every variant, so a new variant can break code in crates that match on your enum.

for a middle

Explain what #[non_exhaustive] changes outside the defining crate: a mandatory wildcard arm, no effect at home, construction of enum variants still allowed.

for a senior

Show you know the attribute must ship with the enum's first release, that variants need their own attribute for new fields, and what the wildcard costs callers.

for a principal

Frame it as a per-type decision: open sets such as errors get the attribute, closed sets stay exhaustive so callers keep compile-time exhaustiveness.

## Why a new variant breaks other crates A Rust `match` must be **exhaustive**: rustc proves at compile time that every possible value of the scrutinee hits an arm. When a downstream crate writes ```rust match err { Error::Timeout => retry(), Error::Connect(host) => report(host), } ``` it is relying on the exact list of variants in the version of the library it compiled against. If the library's next release adds `Error::TooManyRedirects { limit: u32 }`, that same code no longer compiles: rustc 1.99.1 reports `error[E0004]: non-exhaustive patterns: `&httpc::Error::TooManyRedirects { .. }` not covered` for a `match` on `&Error`. No existing variant changed, yet code that built against 1.4.0 fails against 1.5.0. That is precisely what SemVer calls a breaking change, and Cargo's SemVer guide lists it as **Major: adding new enum variants (without non_exhaustive)**. ## What `#[non_exhaustive]` changes outside the defining crate The Reference describes `#[non_exhaustive]` as marking a type or variant that "may have more fields or variants added in the future". It can be put on structs, enums and enum variants, takes no arguments, and has **no effect inside the defining crate**. Outside it, the rules for an enum are: - **Matching**: matching on a variant "does not contribute towards the exhaustiveness of the arms", so every `match` in another crate needs a wildcard `_` arm (or a binding catch-all). Listing every variant that exists today is not enough; rustc still reports E0004 and adds the note that the enum "is marked as non-exhaustive, so a wildcard `_` is necessary to match exhaustively". - **Construction**: values of a non-exhaustive *enum* can still be built (`Error::Connect("example.com".into())` compiles downstream). Only a variant that carries `#[non_exhaustive]` itself is restricted. - **Casts**: an `as` cast to the discriminant is rejected for an enum from another crate that has any non-exhaustive *variant*. | Downstream code | Plain `pub enum Error` | `#[non_exhaustive] pub enum Error` | |---|---|---| | `match` listing every variant, no `_` | compiles until a variant is added | E0004 from day one | | `match` with a `_` arm | compiles | compiles | | `Error::Connect(..)` construction | compiles | compiles | | Adding a variant upstream | **major** | **minor** | Because the wildcard is forced from the first release, nothing that compiles against 1.4.0 can depend on the variant list being closed, so the library may add variants in any minor release. ## Variants and their fields Fields of an enum variant are always public, so the same breakage happens one level down. Cargo's guide lists **Major: adding new fields to an enum variant**: `Error::Connect { host }` gaining a `port` field breaks every downstream constructor and every pattern that names the fields. The mitigations it gives are: 1. Put `#[non_exhaustive]` on the variant itself. Outside the crate it then cannot be constructed (a tuple or unit variant's constructor becomes no more visible than `pub(crate)`), and patterns on it must use braced syntax ending in `..`. 2. Wrap the payload in a struct whose fields you control, such as `Connect(ConnectError)`, and evolve that struct instead. ## When to add the attribute The attribute only helps if it is there **before** anyone writes an exhaustive match. Cargo's guide classifies **adding `#[non_exhaustive]` to an existing enum** as a major change: existing exhaustive matches in other crates stop compiling the moment it appears. So the decision is made when the enum is first published (or in a major release), not in the release that needs the new variant. ## What callers give up The cost is real and falls on the caller: - The `_` arm absorbs future variants silently. A caller who wanted to handle `TooManyRedirects` specially gets no compile error when it appears; they learn about it from release notes. - On stable Rust there is no switch to restore that warning: rustc's `non_exhaustive_omitted_patterns` lint, which reports variants a match skipped behind a wildcard, is still **unstable**. - Error enums, option sets and protocol enumerations are the usual candidates; an enum whose set of values is closed by definition is better left exhaustive, so callers keep the compiler's help. The upshot for the HTTP-client release: if `Error` was published without the attribute, `TooManyRedirects` needs 2.0.0; if it was `#[non_exhaustive]` from the start, 1.5.0 is enough, and the release notes should still tell callers the new variant exists.

  • If a downstream crate lists every current variant of a `#[non_exhaustive]` enum from another crate, does its `match` compile?
    No. Outside the defining crate, matching a variant does not count toward exhaustiveness, so rustc still reports E0004 with the note that the enum is marked as non-exhaustive and a wildcard `_` is necessary. The wildcard is mandatory even when it is unreachable today; that is what guarantees the code survives a new variant.
  • Why not add `#[non_exhaustive]` to `Error` in the same 1.5.0 release that adds the new variant?
    Because adding the attribute to an existing public enum is itself a major change in Cargo's SemVer guide: every downstream exhaustive `match` breaks the moment it appears, new variant or not. The attribute has to be there from the enum's first release, or arrive in a major version.
  • How do you leave room to add a field to the `Error::Connect` variant later?
    Mark the variant itself `#[non_exhaustive]`, so other crates cannot construct it and must use `..` when destructuring it, or make the payload a struct you control, such as `Connect(ConnectError)` with private fields and accessor methods. Adding a field to a plain variant is a major change because all variant fields are public.

  • Adding a variant is minor because no existing variant changed.
  • #[non_exhaustive] forces a wildcard arm inside the defining crate too.
  • Listing every variant downstream satisfies a #[non_exhaustive] enum.
  • #[non_exhaustive] on an enum stops other crates constructing its variants.
  • Adding #[non_exhaustive] in a later minor release keeps everyone compiling.
open as a page

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%

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.

open as a page

Why does moving a dependency from 1.x to 2.0 force a major release of a Rust library whose public function takes that dependency's `Url` type?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Cargo can build 1.x and 2.x of one crate side by side, and their Url types are distinct. Callers passing a 1.x Url to a function now expecting the 2.0 Url get E0308, so the dependency's major bump becomes the library's.

open as a page

When a Rust library adds a method to its public `Middleware` trait, when is that a major release, and why might the crate seal the trait instead?

level: seniorimportance: should knowfreq 38%

basics

~20 s

A method with no default body is major: every outside implementation fails with E0046. A defaulted one is usually safe but can cause E0034 ambiguity. A sealed trait has no outside implementations, so it can gain methods in a minor release.

open as a page

As lead of a widely used Rust HTTP-client crate approaching 1.0, what policy would you set for `#[non_exhaustive]`, deprecation and cutting major versions?

level: principalimportance: should knowfreq 30%

basics

~20 s

Decide before 1.0, type by type: #[non_exhaustive] on error enums, open-ended enums and option structs, exhaustive enums for closed sets. Deprecate with #[deprecated(since, note)] in a minor release, remove only in a major, and batch breaking changes into rare majors.

open as a page

A Rust library's patch release keeps an `Rc` alive across an `.await` inside `pub async fn fetch`; why do some downstream builds stop compiling?

level: seniorimportance: nice to knowfreq 24%

basics

~20 s

Send is an auto trait: the future fetch returns is Send only if everything it holds across .await is Send. An Rc held there removes Send, so callers that need a Send future stop compiling: a breaking change.

open as a page