lotsoftools

Understanding Rust Error E0002: Empty Match Expression on Non-Empty Type

Introduction to Rust Error E0002

Rust Error E0002 occurs when an empty match expression is used with a non-empty type. In safe Rust code, creating an instance of an empty type is impossible, so empty match expressions are almost always undesired. This error is typically resolved by adding one or more cases to the match expression.

What is an Empty Type and a Non-Empty Type?

An empty type is a type that has no possible values, like an enum with no variants. A non-empty type is a type that has at least one possible value, such as a struct or an enum with one or more variants.

Example of an Empty Type

enum Empty { }

In the example above, the 'Empty' enum has no variants, making it an empty type.

Example of a Non-Empty Type

enum Color { Red, Green, Blue }

In this example, the 'Color' enum has three variants, making it a non-empty type.

Empty Match Expression on an Empty Type

fn main() {
    enum Empty {}

    fn foo(x: Empty) {
        match x {
            // empty
        }
    }
}

In the code above, an empty match expression is used with an empty type, and it will compile correctly.

Empty Match Expression on a Non-Empty Type

fn main() {
    fn foo(x: Option<String>) {
        match x {
            // empty
        }
    }
}

In this example, an empty match expression is used with a non-empty type, causing Rust Error E0002.

Fixing Rust Error E0002

To fix Rust Error E0002, add one or more cases to the match expression, like the example below.

fn main() {
    fn foo(x: Option<String>) {
        match x {
            Some(s) => println!("Value: {}", s),
            None => println!("No value"),
        }
    }
}

In this code, the empty match expression has been replaced with two cases, eliminating the E0002 error.