lotsoftools

Rust Error E0409: Inconsistent Variable Binding in Or Patterns

Understanding Rust Error E0409

Rust Error E0409 occurs when an or pattern is used in a match expression, and the variable bindings are not consistently bound across the patterns. This means that a variable is bound by-value in one case and by-reference in another case. In order to fix this error, it is necessary to use the same binding mode in both cases.

Erroneous code example:

#![allow(unused)]
fn main() {
  let x = (0, 2);
  match x {
    (0, ref y) | (y, 0) => { /* use y */ } // error: variable `y` is bound with different mode in pattern #2 than in pattern #1
    _ => ()
  }
}

In this code example, the error occurs because y is bound by-value in the first pattern and by-reference in the second pattern.

Fixing the Error

To fix Rust Error E0409, it is necessary to use the same binding mode in both cases. This can be done by either using ref or ref mut where it is not already used, or by splitting the pattern.

Using the same mode in both cases:

#![allow(unused)]
fn main() {
  let x = (0, 2);
  match x {
    (0, ref y) | (ref y, 0) => { /* use y */ }
    _ => ()
  }
}

In this fixed example, both y bindings are now consistent as they use ref in both cases.

Splitting the pattern:

#![allow(unused)]
fn main() {
  let x = (0, 2);
  match x {
    (y, 0) => { /* use y */ }
    (0, ref y) => { /* use y */}
    _ => ()
  }
}

In this alternative fixed example, the or pattern is split into two separate cases, allowing for the different binding modes to be used without conflict.