Understanding Rust Error E0165
Introduction to Rust Error E0165
Rust Error E0165 occurs when a while let pattern attempts to match an irrefutable pattern. In Rust, pattern matching can be categorized as refutable or irrefutable. A refutable pattern can fail to match, whereas an irrefutable pattern is guaranteed to match, such as a struct constructor with named fields. This article will provide you with information and examples on the correct way to use patterns in Rust loops.
What causes Rust Error E0165
Here is an example of code that would cause Rust Error E0165:
struct Irrefutable(i32);
let irr = Irrefutable(0);
while let Irrefutable(x) = irr {
// ...
}
The compiler raises Error E0165 because it is attempting to match an irrefutable pattern within a while let loop. A while let loop is intended for refutable patterns that may not succeed in matching.
How to fix Rust Error E0165
To fix Rust Error E0165, you must use a regular let-binding inside a loop instead of a while let loop for irrefutable patterns. Here is the corrected code:
struct Irrefutable(i32);
let irr = Irrefutable(0);
loop {
let Irrefutable(x) = irr;
// ...
}
In this corrected code, we've replaced the while let loop with a regular loop and used a let-binding inside for the irrefutable pattern. This code will now compile and execute without error.