]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_error_codes/src/error_codes/E0158.md
Rollup merge of #107190 - fmease:fix-81698, r=compiler-errors
[rust.git] / compiler / rustc_error_codes / src / error_codes / E0158.md
1 An associated `const`, `const` parameter or `static` has been referenced
2 in a pattern.
3
4 Erroneous code example:
5
6 ```compile_fail,E0158
7 enum Foo {
8     One,
9     Two
10 }
11
12 trait Bar {
13     const X: Foo;
14 }
15
16 fn test<A: Bar>(arg: Foo) {
17     match arg {
18         A::X => println!("A::X"), // error: E0158: associated consts cannot be
19                                   //        referenced in patterns
20         Foo::Two => println!("Two")
21     }
22 }
23 ```
24
25 Associated `const`s cannot be referenced in patterns because it is impossible
26 for the compiler to prove exhaustiveness (that some pattern will always match).
27 Take the above example, because Rust does type checking in the *generic*
28 method, not the *monomorphized* specific instance. So because `Bar` could have
29 theoretically infinite implementations, there's no way to always be sure that
30 `A::X` is `Foo::One`. So this code must be rejected. Even if code can be
31 proven exhaustive by a programmer, the compiler cannot currently prove this.
32
33 The same holds true of `const` parameters and `static`s.
34
35 If you want to match against an associated `const`, `const` parameter or
36 `static` consider using a guard instead:
37
38 ```
39 trait Trait {
40     const X: char;
41 }
42
43 static FOO: char = 'j';
44
45 fn test<A: Trait, const Y: char>(arg: char) {
46     match arg {
47         c if c == A::X => println!("A::X"),
48         c if c == Y => println!("Y"),
49         c if c == FOO => println!("FOO"),
50         _ => ()
51     }
52 }
53 ```