skip to content

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%

answer

  1. who implements the trait downstream
  2. default body or not
  3. E0046 and E0034
  4. no outside impls, no outside breakage

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.

solid answer

~50 s

Adding `fn on_request(&self, attempt: u32);` with no body breaks every `impl Middleware for ...` in other crates with E0046 (not all trait items implemented), so it is **major**; so is changing any existing method's signature. With a default body, Cargo's SemVer guide calls it **possibly-breaking**: implementors keep compiling, but a type that also implements another trait with a same-named method gets E0034 (multiple applicable items in scope) wherever `x.method()` is called with both traits in scope. A new method that makes the trait no longer dyn compatible, such as a generic method without `where Self: Sized`, is major for anyone using `dyn Middleware`. **Sealing** the trait so other crates cannot implement it removes the implementor side: methods can then be added in a minor release, but callers lose the ability to write their own implementations.

code

rust · 26 lines
rust
mod httpc {
    pub trait Middleware {
        fn name(&self) -> &str;
        // Added in httpc 1.5.0 with a default body.
        fn retries(&self) -> u32 { 0 }
    }
}

use httpc::Middleware;

// Downstream code written against httpc 1.4.0.
trait RetryPolicy {
    fn retries(&self) -> u32 { 3 }
}

struct Logger;
impl Middleware for Logger {
    fn name(&self) -> &str { "logger" }
}
impl RetryPolicy for Logger {}

fn main() {
    let l = Logger;
    // l.retries() is now E0034: multiple applicable items in scope
    println!("{}: {} vs {}", l.name(), Middleware::retries(&l), RetryPolicy::retries(&l));
}

go deeper

for a junior

Recall that an impl must provide every trait method that lacks a default body, so a new required method breaks implementors.

for a middle

Explain why a defaulted method is only possibly-breaking: E0034 name ambiguity at call sites, which fully qualified syntax resolves.

for a senior

Show the dyn compatibility trap and where Self: Sized, and decide trait by trait whether downstream implementations are part of the contract.

for a principal

Treat sealing as a product decision about extensibility, made at a trait's first release, traded against users' ability to plug in their own types.

## Two audiences for a public trait A public trait has two kinds of users in other crates, and a new method affects them differently: - **Implementors** write `impl Middleware for Logger { ... }`. They must supply every method that has no default body. - **Callers** write `logger.name()` or take `&dyn Middleware` or `impl Middleware`. They depend on method names, signatures and whether the trait can be used as `dyn`. ## Adding a method: Cargo's classification | Change | Cargo SemVer guide | What breaks downstream | |---|---|---| | New method **without** a default body | **Major** | every outside impl: E0046 | | Any change to an existing item's signature | **Major** | outside impls whose signature no longer matches | | New method **with** a default body | **Possibly-breaking** | rare name ambiguity at call sites: E0034 | | New item that makes the trait not dyn compatible | **Major** | every `dyn Middleware` use: E0038 | The **required method** case is mechanical: `impl Middleware for Logger` written against 1.4.0 fails with `error[E0046]: not all trait items implemented, missing: `on_request``. The **defaulted method** case is subtler. Implementors inherit the default and compile. The risk is a **name collision**: if a downstream crate implements its own trait `RetryPolicy` with `fn retries(&self)` for the same type, and the library adds a defaulted `Middleware::retries`, every `logger.retries()` call with both traits in scope fails with `error[E0034]: multiple applicable items in scope`. The fix is fully qualified syntax, `RetryPolicy::retries(&logger)`. Inherent methods do not have this problem, because they take priority over trait methods. Cargo's guide leaves it to each project whether this risk counts as breaking, and advises choosing distinctive names. The **dyn compatibility** case catches people out: a defaulted generic method `fn with<T>(&self, t: T) -> T` makes `Box<dyn Middleware>` fail with `error[E0038]: the trait `Middleware` is not dyn compatible`. Adding `where Self: Sized` to that method keeps the trait usable as `dyn` (the method is simply unavailable on trait objects). ## Sealing as a design decision A **sealed trait** is public to call but impossible to implement outside its crate. The usual construction is a supertrait that other crates cannot name (that construction is covered with typestate builders). What matters for evolution is the effect: - **No downstream implementations exist**, so the implementor column of the table disappears. The Rust API Guidelines say the crate is "free to add methods" to a sealed trait in a non-breaking release, even methods with no default body. - **Callers are still users.** Removing a public method or changing its signature is still breaking, and the same rare call-site ambiguity as a defaulted method can still arise. - **The cost is flexibility.** Other crates cannot plug in their own types, and test fakes for the trait must come from the library. Document in rustdoc that the trait is sealed so people do not try. ## Making a defaulted addition safe - Give the default the behaviour every existing implementor had implicitly before; for a hook, that usually means doing nothing. - Pick a name unlikely to clash: `on_request` collides less often than `retries` or `name`. - Keep the method dyn compatible: no generic type parameters and no by-value `Self` return unless the method carries `where Self: Sized`. - Say in the release notes that the method exists, so implementors know they may override it. ## Choosing for `Middleware` The deciding question is whether other crates are **meant** to implement the trait: 1. A trait that exists so users can plug in behaviour (custom middleware, logging hooks) cannot be sealed. Evolve it by adding defaulted methods with distinctive names, keep it dyn compatible, and save required methods or signature changes for a major release. 2. A trait the library implements for its own types and users only call (a `Body` trait over the crate's own body types, say) is a good candidate for sealing from its first release. 3. Sealing an existing open trait is itself breaking, because it rejects implementations that compiled before. So for the HTTP-client release: a new `on_request` hook on an open `Middleware` trait ships in a minor version only with a default body (for example one that does nothing); without one it needs a major version.

  • Why can a new generic method with a default body still be a major change for a Rust trait?
    A generic method makes the trait not dyn compatible, so every `Box<dyn Middleware>` or `&dyn Middleware` in other crates fails with E0038. Cargo's guide lists this as major. Adding `where Self: Sized` to the new method keeps the trait dyn compatible; the method just cannot be called on a trait object.
  • Once a Rust trait is sealed, is every change to it non-breaking?
    No. Sealing removes downstream implementations, so adding methods becomes safe, but callers still exist: removing a public method or changing a public method's signature still breaks them. Sealing an existing open trait is also breaking, since it rejects implementations that already compiled.

  • A new trait method with a default body can never break anyone.
  • Adding a required method is minor because existing callers still compile.
  • Sealing a trait lets you change existing public method signatures freely.
  • Seal every public trait by default; downstream impls are never needed.
  • A generic default method has no effect on dyn Middleware users.