Rust, Software Development

Using #[non_exhaustive] for Non-exhaustive Enums

Using non-exhaustive enums in one crate prevents codes in other crates from listing all the possible matches in a match expression. It forces developers to use wildcards and thereby making the match expression non-exhaustive. By having a non-exhaustive match expression, it future-proofs our codes. Note that it has no effect when we use it in the same crate. For our example, we have two projects wherein one uses the other.

Future-Proof Project

This crate does not have dependencies and only has a single public enum.

Cargo.toml

lib.rs with Non-Exhaustive Enum

The Countries enum contains six items. It uses two metadata. The first makes it printable; while the second makes it non-exhaustive enum using #[non_exhaustive]

Build it to make sure there are no errors.

A crate with #[non_exhaustive] Enums

Project  With Non-Exhaustive Match Expression

Cargo.toml

This crate uses the abovementioned crate.

main.rs

When we build this project, we will get the following:

A crate the uses a #[non_exhaustive] Enums

To fix this error, modify the codes as follow. In the new codes, the matching expression is no longer exhaustive for the non-exhaustive enum. The codes will remain unchanged even if there are new enum items.

We tested the codes with Rust 1.40.0. For more information, please visit the non-exhaustive attribute.

Non-Exhaustive Struts

The non-exhaustive attribute can also make Structs non-exhaustive.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like