Sling Academy
Home/Rust/Rust - Enum Exhaustiveness and Future-Proofing with `#[non_exhaustive]`

Rust - Enum Exhaustiveness and Future-Proofing with `#[non_exhaustive]`

Last updated: January 04, 2025

When working with enums in Rust, one of the language's compelling features is pattern matching. It provides exhaustive checks to ensure all possibilities are covered, helping you catch logical errors during compilation. However, what happens when you consider future-proofing your Rust application? This is where the #[non_exhaustive] attribute becomes significant.

The #[non_exhaustive] attribute modifies an enum (or a struct) so that new variants can be added in the future without breaking existing codebases. This approach helps ensure your libraries remain backward compatible as APIs evolve. Let's delve deeper into how this can be applied effectively.

Understanding Enums and Pattern Matching

An enum in Rust is a type that represents data that can be one of several different variants. For example, consider an enum defining the states of a traffic light:

enum TrafficLight {
    Red,
    Green,
    Yellow,
}

One likely use for this enum is to handle these states with pattern matching:

fn show_light_state(light: TrafficLight) {
    match light {
        TrafficLight::Red => println!("Stop"),
        TrafficLight::Green => println!("Go"),
        TrafficLight::Yellow => println!("Get ready"),
    }
}

Rust will enforce that all possible variants are covered. If you omit any variant, the code won't compile, forcing you to handle all potential cases.

Introducing #[non_exhaustive]

In scenarios where you foresee additions to your enum, it can be beneficial to prepare for it without forcing all user code to update in lockstep. The #[non_exhaustive] attribute, therefore, indicates that more variants might be added in the future:

#[non_exhaustive]
enum Status {
    Success,
    Warning,
    Error,
}

When pattern matching against a #[non_exhaustive] enum, you must handle the possibility of other, future variants. Often, this is achievable by including a wildcard arm (_) in the match statement:

fn handle_status(status: Status) {
    match status {
        Status::Success => println!("Operation successful"),
        Status::Warning => println!("Warning: Check the details"),
        Status::Error => println!("Error occurred"),
        _ => println!("Unknown status"), // handles all future variants
    }
}

Use Cases for #[non_exhaustive]

The #[non_exhaustive] attribute is applicable in several scenarios involving both enums and structs. Some examples include:

  • API Evolution: Publishing a public API with the flexibility to introduce new features over time.
  • Feature Flags: Handling toggled features dynamically within an application where adaptation is essential.
  • Protocol Development: Creating systems where responses and request types may expand.

Benefits of Non-Exhaustive Enums

Using the #[non_exhaustive] attribute brings several advantages:

  • Flexibility: Allows library authors to extend enums and structs without breaking existing implementations.
  • Stability: Reduces the risk of software failure when enums grow over time with advancing versions.
  • Compatibility: Maintains backward compatibility without immediately breaking consuming code.

Conclusion

To sum up, the #[non_exhaustive] attribute in Rust provides you with a mechanism to future-proof your enums and structs, enabling flexibility, and safeguarding your libraries' evolution. This proactive approach to API design ensures less friction as your software grows, allowing for seamless updates that enhance your existing capabilities without unforeseen breaks.

Next Article: Rust - Nested Matches: Handling Multiple Layers of Enum Wrapping

Previous Article: Rust - Comparing Enums with PartialEq and Derivable Traits

Series: Enum and Pattern Matching in Rust

Rust

You May Also Like

  • E0557 in Rust: Feature Has Been Removed or Is Unavailable in the Stable Channel
  • Network Protocol Handling Concurrency in Rust with async/await
  • Using the anyhow and thiserror Crates for Better Rust Error Tests
  • Rust - Investigating partial moves when pattern matching on vector or HashMap elements
  • Rust - Handling nested or hierarchical HashMaps for complex data relationships
  • Rust - Combining multiple HashMaps by merging keys and values
  • Composing Functionality in Rust Through Multiple Trait Bounds
  • E0437 in Rust: Unexpected `#` in macro invocation or attribute
  • Integrating I/O and Networking in Rust’s Async Concurrency
  • E0178 in Rust: Conflicting implementations of the same trait for a type
  • Utilizing a Reactor Pattern in Rust for Event-Driven Architectures
  • Parallelizing CPU-Intensive Work with Rust’s rayon Crate
  • Managing WebSocket Connections in Rust for Real-Time Apps
  • Downloading Files in Rust via HTTP for CLI Tools
  • Mocking Network Calls in Rust Tests with the surf or reqwest Crates
  • Rust - Designing advanced concurrency abstractions using generic channels or locks
  • Managing code expansion in debug builds with heavy usage of generics in Rust
  • Implementing parse-from-string logic for generic numeric types in Rust
  • Rust.- Refining trait bounds at implementation time for more specialized behavior