Rust errors / Types and traits
Rust compiler error · checked with rustc 1.99.0
Rust error E0408: variable `y` is not bound in all patterns
What it meansAn "or" pattern was used where the variable bindings are not consistently bound across patterns.
What rustc prints
error[E0408]: variable `y` is not bound in all patterns
--> main.rs:4:15
|
4 | Some(y) | None => { /* use y */ } // error: variable `y` from pattern #1 is
| - ^^^^ pattern doesn't bind `y`
| |
| variable not in all patternsReal 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
An "or" pattern was used where the variable bindings are not consistently bound across patterns.
Erroneous code example:
match x {
Some(y) | None => { /* use y */ } // error: variable `y` from pattern #1 is
// not bound in pattern #2
_ => ()
}
Here, y is bound to the contents of the Some and can be used within the block corresponding to the match arm. However, in case x is None, we have not specified what y is, and the block will use a nonexistent variable.
To fix this error, either split into multiple match arms:
let x = Some(1);
match x {
Some(y) => { /* use y */ }
None => { /* ... */ }
}
or, bind the variable to a field of the same type in all sub-patterns of the or pattern:
let x = (0, 2);
match x {
(0, y) | (y, 0) => { /* use y */}
_ => {}
}
In this example, if x matches the pattern (0, _), the second field is set to y. If it matches (_, 0), the first field is set to y; so in all cases y is set to some value.
From rustc --explain E0408 (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
- E0405cannot find trait `SomeTrait` in this scope
- E0407method `b` is not a member of trait `Foo`
- E0409variable `y` is bound inconsistently across alternatives separated by `|`
- E0411cannot find type `Self` in this scope
Up next
Often hit nextE0308: mismatched typesA related error from the same family.Read it next →Did this answer your question?