E0158 - Error codes index
Description: Book listing all Rust error codes

# Error code E0158

An associated `const`, `const` parameter or `static` has been referenced in a pattern.

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")
        }
    }
    }

Associated `const`s cannot be referenced in patterns because it is impossible for the compiler to prove exhaustiveness (that some pattern will always match). Take the above example, because Rust does type checking in the generic method, not the monomorphized specific instance. So because `Bar` could have theoretically infinite implementations, there's no way to always be sure that `A::X` is `Foo::One`. So this code must be rejected. Even if code can be proven exhaustive by a programmer, the compiler cannot currently prove this.

The same holds true of `const` parameters and `static`s.

If you want to match against an associated `const`, `const` parameter or `static` consider using a guard instead:

    #![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"),
            _ => ()
        }
    }
    }