lotsoftools

Understanding Rust Error E0158

Introduction to Rust Error E0158

Rust Error E0158 occurs when an associated constant, const parameter, or static is referenced in a pattern. The Rust compiler cannot prove exhaustiveness, meaning that it's unable to guarantee that some pattern will always match.

Original Erroneous Code Example

#![allow(unused)]
fn main() {
enum Foo {
    One,
    Two
}

trait Bar {
    const X: Foo;
}

fn test<A: Bar>(arg: Foo) {
    match arg {
        A::X => println!("A::X"), // error: E0158: associated consts cannot be
                                  //        referenced in patterns
        Foo::Two => println!("Two")
    }
}
}

Explanation of Error E0158

In the code example, E0158 occurs because the match statement references the associated constant A::X. Rust performs type checking in the generic method, rather than the monomorphized specific instance. Since there can be an infinite number of Bar implementations, the compiler cannot guarantee exhaustive matching for A::X.

Solution to Rust Error E0158

To resolve this error, use a guard instead of directly referencing associated consts, const parameters, or statics in the pattern. This ensures that the code compiles and runs correctly.

Corrected Code Example

#![allow(unused)]
fn main() {
trait Trait {
    const X: char;
}

static FOO: char = 'j';

fn test<A: Trait, const Y: char>(arg: char) {
    match arg {
        c if c == A::X => println!("A::X"),
        c if c == Y => println!("Y"),
        c if c == FOO => println!("FOO"),
        _ => ()
    }
}
}

Conclusion

To avoid Rust Error E0158, use guards instead of referencing associated consts, statics, or const parameters within a pattern. This will enable the compiler to handle the code properly and ensure optimal performance.