lotsoftools

Understanding Rust Error E0638: Non-exhaustive Matching

Introduction to Rust Error E0638

Rust Error E0638 occurs when a struct, enum or enum variant marked as non_exhaustive is not matched in a non-exhaustive manner. This means that the _ pattern must be used while matching enums and the .. pattern must be used while matching structs.

Why Does Error E0638 Occur?

The error occurs in downstream crates when non-exhaustive enums are not matched with a wildcard (_) pattern, or when structs are not matched using the .. pattern. Non-exhaustive enum variants cannot be matched against in downstream crates.

How to Recognize Error E0638

Consider the following example where the enum Error is marked as non-exhaustive:

#[non_exhaustive]
pub enum Error {
    Message(String),
    Other,
}

It is necessary for downstream crates to match enums non-exhaustively:

use mycrate::Error;

match error {
    Message(s) => ...,
    Other => ...,
    _ => ...,
}

The above code will not produce an error, as the non_exhaustive Error enum is matched with a wildcard (_).

For structs, the match should be done using the .. pattern to avoid this error.

How to Fix Error E0638

To fix Rust Error E0638, simply ensure that enums marked as non_exhaustive are matched using the _ pattern, and structs are matched using the .. pattern in downstream crates.

In the case of enums, add the _ pattern to the match expression:

match error {
    Message(s) => ...,
    Other => ...,
    _ => ...,
}

For structs, use the .. pattern to designate non-exhaustive matching:

match struct_example {
    StructName { field1, field2, .. } => ...,
}

Following these guidelines will resolve Rust Error E0638.