Rust errors / Types and traits
Rust compiler error · checked with rustc 1.99.0
Rust error E0158: constant pattern cannot depend on generic parameters
What it meansA generic parameter or static has been referenced in a pattern.
What rustc prints
error[E0158]: constant pattern cannot depend on generic parameters
--> main.rs:12:9
|
6 | trait Bar {
| ---------
7 | const X: Foo;
| ------------ constant defined here
...
10 | fn test<A: Bar>(arg: Foo) {
| - constant depends on this generic parameter
11 | match arg {
12 | A::X => println!("A::X"), // error: E0158: constant pattern depends
| ^^^^ `const` depends on a generic parameterReal output of rustc 1.99.0 compiling the official example below (2021 edition). Your names and line numbers will differ; the first line is the part to match.
The compiler team's explanation
A generic parameter or static has been referenced in a pattern.
Erroneous code example:
enum Foo {
One,
Two
}
trait Bar {
const X: Foo;
}
fn test<A: Bar>(arg: Foo) {
match arg {
A::X => println!("A::X"), // error: E0158: constant pattern depends
// on a generic parameter
Foo::Two => println!("Two")
}
}
Generic parameters 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 arbitrary 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 statics.
If you want to match against a const that depends on a generic parameter or a static, consider using a guard instead:
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"),
_ => ()
}
}From rustc --explain E0158 (1.99.0), part of the Rust project, MIT or Apache-2.0. Official page.
Related errors
- E0308mismatched types
- E0277the trait bound is not satisfied
- E0599no method named X found in the current scope
- E0433failed to resolve
- E0128generic parameter defaults cannot reference parameters before they are declared
- E0131The `main` function was defined with generic parameters
- E0170pattern binding `GET` is named the same as one of the variants of the type `Method`
- E0178expected a path on the left-hand side of `+`
Up next
Often hit nextE0308: mismatched typesA related error from the same family.Read it next →Did this answer your question?