Explain the non_exhaustive attribute on enums—how does it enforce forward compatibility…
- User
Explain the
non_exhaustiveattribute on enums—how does it enforce forward compatibility for libraries? Assistant
Explain the non_exhaustive attribute on enums—how does it enforce forward compatibility for libraries?
1. Analyze the Request:
* Topic: The #[non_exhaustive] attribute in Rust.
* Focus: Enums (though it applies to structs too, the user specifically asked about enums).
* Goal: Explain how it enforces forward compatibility for libraries.
Deconstruct the Concept (#[non_exhaustive]):
Drafting the Explanation - Step-by-Step:
Introduction:
#[non_exhaustive].The Problem (Without non_exhaustive):
my_lib with an enum Color { Red, Green }.match color { Red => ..., Green => ... }.Blue.Blue). This is a breaking change.The Solution (With #[non_exhaustive]):
#[non_exhaustive] to Color._.Blue._ catches Blue.Key Effects/Restrictions (The "How"):
_ (wildcard) arm in match expressions.Enum::A outside the defining crate (for structs) or struct-like variants (though for simple enum variants, you usually can still select them if they are visible, but construction of the enum type might be restricted in specific ways, actually, for enums, it mainly affects matching and constructing struct-like variants). Self-correction: For enums, the main restriction is on matching. You can usually still refer to existing variants. Wait, let me double-check construction rules.
let x = MyEnum::A; if MyEnum is non-exhaustive? Let's verify.let e = Error::Timeout; if it's non-exhaustive. You rely on the library giving you instances._.let e = MyEnum::A;? Check: Actually, no. If an enum is #[non_exhaustive], you cannot construct it at all from outside the crate using the Enum::Variant syntax. This ensures the library can add fields required for construction later (if it changes to a struct variant) or ensures the library controls creation.match e { MyEnum::A => ... } works, but let x = MyEnum::A; fails.A to A(u32) later, MyEnum::A would be a compilation error in the client code. By disallowing construction, the library protects that API surface.Struct vs. Enum Context (Briefly):
..Default).Detailed Breakdown of "Forward Compatibility":
Error::Network, user code with _ => handles it gracefully.Code Examples:
_, library adds variant, user code compiles and runs (often hitting the fallback logic).Caveats/Downsides:
_ arm usually being unreachable if all known variants are covered, but here it is required.Refining the Structure of the Answer:
lib.rs vs main.rs example.Self-Correction/Double Check during drafting:
#[non_exhaustive] prevent accessing fields of struct variants?#[non_exhaustive] enum E { A, B }, can I do let e = E::A;?E::A is a valid pattern, but not a valid constructor expression outside the crate. Error: "cannot create non-exhaustive enum". This is a crucial detail to include.Final Polish: Ensure the tone is helpful and technical but accessible. Use formatting (bolding, code blocks) effectively.
(Self-Correction regarding Construction of Enum Variants): Actually, this is slightly nuanced. If the enum is non-exhaustive, you cannot construct it at all from outside the crate using standard syntax. However, you can match on specific variants. Example:
// Lib
#[non_exhaustive]
pub enum E { A, B }
// User
match e {
E::A => ..., // Allowed
_ => ...
}
let x = E::A; // Error: cannot create non-exhaustive enum
Why? Because the library might want to add data to A later (e.g., A(u32)). If the user constructed E::A, changing it to A(u32) would break the user's code. By forbidding construction, the lib author preserves the right to add data to existing variants.
Constructing the Final Output: (Proceeding to generate response based on these points).
#[non_exhaustive] attribute in Rust is a tool for library maintainers to achieve Application Binary Interface (ABI) stability and source-level backward compatibility when evolving their APIs.When applied to an enum, it tells the compiler: "This list of variants may grow in the future. Code outside of this crate must handle that possibility."
Here is a detailed explanation of how it works and why it enforces forward compatibility.
By default, Rust enums are exhaustive. When you define a public enum, the compiler forces consumers (users of your library) to handle every single variant explicitly.
Library Code (v1.0):
pub enum Error {
NotFound,
PermissionDenied,
}
Consumer Code:
match error {
Error::NotFound => println!("Missing"),
Error::PermissionDenied => println!("No access"),
// No default branch needed because the compiler knows we covered everything.
}
The Breaking Change:
If the library releases v2.0 and adds a new variant, Error::Timeout, the consumer's code will fail to compile. The compiler will complain that the match is non-exhaustive and the new variant Timeout is not covered.
This makes adding variants a breaking change, often forcing a major version bump (e.g., 1.0 to 2.0) just for adding a single option.
#[non_exhaustive]By adding #[non_exhaustive] to the enum definition, the library author signals that variants may be added in the future.
Library Code (v1.0):
#[non_exhaustive]
pub enum Error {
NotFound,
PermissionDenied,
}
This enforces two strict rules on the consumer:
_ Arm)Consumers can no longer match only the known variants. The compiler forces them to include a wildcard arm (_ or ..) to handle future, unknown variants.
Consumer Code:
match error {
Error::NotFound => println!("Missing"),
Error::PermissionDenied => println!("No access"),
// COMPILER ERROR: non-exhaustive patterns
// The consumer MUST add:
_ => println!("Unknown error occurred"),
}
The Result:
When the library releases v2.0 and adds Error::Timeout, the consumer's code does not break. The match expression is valid because the new variant simply falls into the _ (catch-all) arm.
#[non_exhaustive] also prevents consumers from constructing the enum using struct-like or default syntax outside the defining crate.
While this applies heavily to structs (preventing Struct { field: value }), for enums, it primarily prevents consumers from relying on the existence of a specific variant count or using functional construction patterns that might break if variants are added. Effectively, it treats the enum as a type that is "defined" and "evolved" solely by the library.
Forward compatibility (or backward compatibility for the library) means that code written today will continue to work with future versions of the library.
non_exhaustive, a new variant causes a compile-time error. With it, the code compiles and runs (directing logic to the fallback branch).match statements. Without this attribute, adding a variant legally requires a major version bump (2.0).When you mark an enum #[non_exhaustive], consumers of your library face these restrictions:
| Action | Without Attribute | With #[non_exhaustive] |
|---|---|---|
| Matching | Can match strictly known variants. | Must include a wildcard arm (_). |
| Construction | Can construct explicitly. | Construction is usually restricted; consumers treat it as a received value rather than one they create. |
| Evolution | Adding variants breaks consumer compilation. | Adding variants is safe; consumer code relies on wildcards. |
Imagine you are writing a library for a Smart Home system.
// lib.rs (v1.0)
#[non_exhaustive]
pub enum DeviceState {
Online,
Offline,
}
A user writes an app using your library:
// user_app.rs
fn check_device(state: DeviceState) {
match state {
DeviceState::Online => println!("Connected"),
DeviceState::Offline => println!("Disconnected"),
_ => println!("Device is in a new/unknown state"),
}
}
Six months later, you update your library to support a new feature:
// lib.rs (v1.1)
#[non_exhaustive]
pub enum DeviceState {
Online,
Offline,
Sleeping, // New variant added
Updating, // Another new variant
}
The user updates their dependencies to v1.1. Their code compiles successfully without a single change. The Sleeping and Updating states are gracefully handled by the _ wildcard, printing "Device is in a new/unknown state."
This is the power of #[non_exhaustive]: it allows the library to grow without breaking the world around it.