Hello everyone, recently I have come across a feature in Rust, known as non_exhaustive
. It was introduced in Rust 1.40.0 . This attribute prevents source code-breaking changes in projects downstream.
enums
can be non-exhaustive or exhaustive, depending upon their needs. A non-exhaustive enum indicates that this enum may get new value in the future. By adding #[non_exhaustive]
attribute, we can create a non-exhaustive enum which forces downstream crates to use wildcard pattern (_
) in the match expression and make it non-exhaustive. Otherwise, we will get the compilation error.
Let’s see with a simple example.
cargo new
and define a rust module movie_genres
under this project.lib.rs
and add an enum for movie genres with #[non_exhaustive]
attribute.#[non_exhaustive]
pub enum Genres {
Horror,
Comedy,
Romance,
}
Cargo.toml
add the dependency.movie_genres = {version = "0.1.0", path="./movie_genres"}
movie_genres
in main.rs
and start testing.extern crate movie_genres;
use movie_genres::Genres;
fn main() {
let genres = Genres::Horror;
match genres {
Genres::Horror => println!("Horror Movie!!"),
Genres::Comedy => println!("Comedy Movie!!"),
Genres::Romance => println!("Romance Movie!!"),
}
}
cargo run
, we will get a compilation error. match genres {
Genres::Horror => println!("Horror Movie!!"),
Genres::Comedy => println!("Comedy Movie!!"),
Genres::Romance => println!("Romance Movie!!"),
_ => println!("Other movie category"),
}
#rust #enumerations #rust programming language #rust projects