lotsoftools

Understanding Rust Error E0297

Overview of Rust Error E0297

Rust Error E0297 occurs when the pattern used to bind names is not irrefutable, meaning it doesn't guarantee that a name will be extracted in all cases. To resolve this issue, it is suggested to use a match or if let inside the loop body.

Example of an incorrect pattern match

let xs: Vec<Option<i32>> = vec![Some(1), None];

// This fails because `None` is not covered.
for Some(x) in xs {
    // ...
}

Solution 1: Using match inside the loop

let xs: Vec<Option<i32>> = vec![Some(1), None];

for item in xs {
    match item {
        Some(x) => {},
        None => {},
    }
}

Solution 2: Using if let inside the loop

let xs: Vec<Option<i32>> = vec![Some(1), None];

for item in xs {
    if let Some(x) = item {
        // ...
    }
}

Explanation of the solutions

In the first solution, match is used inside the loop to cover both Some and None cases. It ensures that a name will be extracted in all cases. In the second solution, if let is used that allows more compact handling of the Some case while ignoring the None case. Both solutions satisfy the requirement for irrefutable patterns, thus eliminating Rust Error E0297.