Evolving Public APIs in Rust


In this post

A library is a promise about its types

A small health-check library ships three public items:

pub enum Status {
    Up,
    Down,
}

pub struct Report {
    pub url: String,
    pub status: Status,
}

pub trait Notifier {
    fn deliver(&self, report: &Report);
}

Every public item like this makes promises, and the promises are not about the code the library runs. They are about what downstream code can do with the types. A caller today can write all of this:

use health::{Notifier, Report, Status};

struct Webhook;

impl Notifier for Webhook {
    fn deliver(&self, report: &Report) {
        match report.status {
            Status::Up => println!("up"),
            Status::Down => println!("down"),
        }
    }
}

fn main() {
    let report = Report {
        url: String::from("https://example.com/health"),
        status: Status::Up,
    };
    Webhook.deliver(&report);
}

The caller constructs a Report with a struct literal, matches a Status exhaustively, and implements Notifier for its own type. Three abilities, three promises the library has now made: downstream code may construct, may match, and may implement. The earlier post on modeling data with Rust’s type system made the general point that public types are contracts; this post walks what each promise costs and which tool buys it back.

Three changes, three breaks

The library grows. It adds a Degraded status, a checked_at timestamp to the report, and a timeout configuration to the notifier. All three are changes the library wants, and each one breaks a different caller:

error[E0004]: non-exhaustive patterns: `Status::Degraded` not covered
   |
   |         match report.status {
   |               ^^^^^^^^^^^^^ pattern `Status::Degraded` not covered
error[E0063]: missing field `checked_at` in initializer of `health::Report`
   |
   |     let report = Report {
   |                  ^^^^^^ missing `checked_at`
error[E0046]: not all trait items implemented, missing: `timeout`
   |
   | impl Notifier for Webhook {
   | ^^^^^^^^^^^^^^^^^^^^^^^^^ missing `timeout` in implementation
   |
   = help: implement the missing item: `fn timeout(&self) -> u64 { todo!() }`

Compiler output in this post is abridged to the lines that matter. Each error lands in the caller’s code, not the library’s, and each one corresponds to exactly one promise: the new variant broke an exhaustive match, the new field broke a struct literal, the new required method broke an implementation. The third message is even helpful in a painful way — the help: line writes the code the caller must now add to stay compatible. Cargo’s semver reference classifies all three changes the same way, as major: adding new enum variants, adding a public field when no private field exists, and adding a non-defaulted trait item.

None of this is a compiler quirk. The caller’s code genuinely depends on the shape the library declared yesterday, and the library changed that shape. The changes are needed, so the question is which promises to stop making.

Default methods

The Notifier promise is the cheapest one to soften. A trait method with a body is a method the caller does not have to implement:

pub trait Notifier {
    fn deliver(&self, report: &Report);
    fn timeout(&self) -> u64 {
        5
    }
}

Adding this to a released trait leaves the caller’s code compiling unchanged — there is nothing missing from its impl, because the method now has a body in the trait definition. The semver reference still files defaulted-item additions under “possibly-breaking”, because a caller whose type already has an inherent method with that name can see its method resolution change. In the common case, though, a default turns a major version bump into a plain feature release.

The limit of this tool is also visible in the code. The default body runs for every caller that does not override it, so the library can only pick behavior that is safe for all of them. A timeout default of five seconds is a policy choice the library must be willing to own — and changing that default later changes behavior for callers who never wrote it down. The trait stays open to additions, but each addition carries a behavior commitment.

#[non_exhaustive]: selling construction and matching back

For the enum and the struct, Rust has a dedicated attribute. The reference describes #[non_exhaustive] as a marker that the type is not complete, and it behaves differently at each of the three places it can sit — on an enum, on a variant, or on a struct. The differences are easy to mix up, so this section keeps them separate.

On an enum

The overview post introduced this level: marking the whole enum tells downstream matchers that the variant list is not final.

#[non_exhaustive]
pub enum Status {
    Up,
    Down,
    Degraded,
}

The caller’s old match — one arm per variant — no longer compiles, but the failure has changed shape:

error[E0004]: non-exhaustive patterns: `_` not covered

The compiler no longer names the missing variant, because the variant list is not part of the contract. A caller that adds a _ arm compiles, and stays compiling: when the library later ships Status::Maintenance, that caller’s build does not notice. This is the payoff — additions stop breaking matches.

Two details qualify it. First, matching is what got restricted; constructing did not. A downstream caller can still write Status::Up — the listed variants remain constructible. Second, the _ arm is a blind spot by design: the library can add variants that the caller’s code silently treats as “anything else”. A status that used to produce a compile-time gap now flows through the caller’s fallback branch. Exhaustiveness checking was the caller’s safety net for additions; giving it up is what makes room for them.

On a variant

Marking a single variant is a different promise:

pub enum Status {
    Up,
    Down,
    #[non_exhaustive]
    Degraded { reason: String },
}

The reason field is now an implementation detail, and that matters for the roadmap: adding a field to an already-released ordinary variant is itself a major change, so this is the fix that moves that addition behind the rest pattern. A caller matching the variant must use a rest pattern inside the braces, and the compiler explains exactly where:

error[E0638]: `..` required with variant marked as non-exhaustive
   |
   |         Status::Degraded { reason } => println!("degraded: {reason}"),
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
help: add `..` at the end of the field list to ignore all other fields
   |
   |         Status::Degraded { reason , .. } => println!("degraded: {reason}"),
   |                                   ++++

Construction is gone entirely, not just relaxed:

error[E0639]: cannot create non-exhaustive variant using struct expression

This is the contrast to keep in mind: an #[non_exhaustive] enum still lets callers build the variants it lists; an #[non_exhaustive] variant lets nobody outside the crate build it at all. The library gains field freedom — it can add a checked_at to Degraded without a major bump — and downstream code can only obtain the variant from the library itself.

On a struct

On a struct, the attribute does what it does on a variant, applied to the whole type:

#[non_exhaustive]
pub struct Report {
    pub url: String,
    pub status: Status,
}

A downstream struct literal now fails, and functional update syntax with a library-provided base value fails the same way:

error[E0639]: cannot create non-exhaustive struct using struct expression
   |
   |     let r = Report { status: Status::Down, ..base };
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Matching the struct requires .., the same as a variant. The construction ban is strict on purpose: Cargo’s semver reference spells it out — non-exhaustive structs “cannot be constructed using struct literal syntax, including functional update syntax”. The only way to get a Report is through the library’s own functions or builders, which is exactly the shape the smart constructors post recommended for types with invariants. The attribute generalizes that advice: a type that callers cannot build is a type the library can reshape.

The payoff shows up in the same shape as with the enum: once Report carries the attribute, the library adds a checked_at field, and callers who match with .. and read only the old fields compile unchanged. The attribute does not protect field access. A caller compiled against the newer library can read checked_at by name, and if the library ever removes a published field, that is a break no attribute softens. Field addition is where the freedom lands, and that is the change libraries most often need.

Sealed traits

Default methods keep a trait open to methods. Sealing goes further and closes it to implementations:

mod sealed {
    pub trait Sealed {}
    impl Sealed for super::HttpNotifier {}
}

pub trait Notifier: sealed::Sealed {
    fn deliver(&self, report: &Report);
}

pub struct HttpNotifier;

impl Notifier for HttpNotifier {
    fn deliver(&self, report: &Report) { /* ... */ }
}

Notifier is public, but its supertrait Sealed lives in a private module, so no downstream type can ever implement it. The caller who tries gets a bound it cannot satisfy:

error[E0277]: the trait bound `Webhook: health::sealed::Sealed` is not satisfied
   |
   | impl Notifier for Webhook {
   |                   ^^^^^^^ unsatisfied trait bound
   |
help: the trait `health::sealed::Sealed` is not implemented for `Webhook`

A second help line lists the types that do implement Sealed — the library’s own — so the message also answers the question of who may implement the trait.

Sealing is a heavier decision than the other tools, because it removes an ability outright: no Webhook, no third-party notifiers, ever. The compensation is freedom on the implementation side. With downstream implementations out of the picture, the library can add required methods or change existing ones without breaking a single impl — call sites still constrain method signatures, but the implementor half of the contract disappears. The Rust API Guidelines call this pattern C-SEALED and recommend it for traits that only exist to be called, not implemented. The test is whether the trait is part of the library’s interface or of its internals. If callers never need their own implementations, the promise “you may implement this” is a promise the library should not be making.

#[deprecated]: the gentle path

Everything above changes what compiles. The last tool changes what gets recommended, and breaks nothing:

#[deprecated(note = "use `Report::builder` instead")]
pub fn make_report_v1(url: &str) -> Report {
    Report::builder(url).build()
}

Callers still compile, and their builds print:

warning: use of deprecated function `health::make_report_v1`: use `Report::builder` instead
   |
   |     let u = health::make_report_v1("https://x");
   |                     ^^^^^^^^^^^^^^
   |
   = note: `#[warn(deprecated)]` on by default

The note lands in the caller’s warning output with the replacement named. Deprecation is the one tool in this post that can be applied to an existing release with no risk of breaking callers: the old function stays callable while every build nudges toward the new one. It pairs naturally with the rest — mark the old path deprecated, ship the new one, and remove the old path in the next major version.

Versions: 0.x is the rehearsal

These tools have a hard timing constraint, and it comes from how they work. Every one of them operates by removing an ability: matching exhaustively, constructing literally, implementing freely. Removing an ability from code that already relies on it is a break. So the freedom the tools buy only exists if they ship before the promise is made — #[non_exhaustive] on day one keeps variants addable forever, while adding it after release breaks every downstream match, which is the kind of change the attribute exists to make unnecessary.

This is what the version numbers are for. Cargo’s semver reference lets “0.y.z” releases treat a change in y as a major version, so a pre-1.0 library can break its callers as it learns — add Degraded to a plain enum in 0.1, watch downstream matches fail, ship #[non_exhaustive] in 0.2. At 1.0 the contract locks, and the attributes have to be there already. The rehearsal framing is the practical takeaway: these compile errors are information to gather while the contract can still change.

The library then commits to one set of promises, and the vocabulary is small enough to state plainly. Construction stays open only for types that will never grow fields. Matching stays exhaustive only for enums that are truly closed, like a Protocol with two fixed values. Traits stay implementable only when callers genuinely need implementations. Everything else gets #[non_exhaustive], defaults, or a sealed supertrait — and the three error messages from the middle of this post become design decisions made in advance instead of breaks discovered in a caller’s build.

<— back to rust