Understanding Rust Error E0162

About Rust Error E0162

Rust error E0162 refers to a pattern matching situation where an irrefutable pattern is used with an if let expression. An irrefutable pattern is one that always matches, making it inappropriate for conditional expressions like if let, which are meant to handle cases where a pattern might not match. Rather than using if let with an irrefutable pattern, a regular let-binding should be used instead.

Error E0162 Example

Consider the following Rust code that causes error E0162:

struct Irrefutable(i32);
let irr = Irrefutable(0);

// This fails to compile because the match is irrefutable.
if let Irrefutable(x) = irr {
    // This body will always be executed.
    // ...

In this example, the struct Irrefutable has a single tuple field, making it an irrefutable pattern. Using it in an if let expression will result in error E0162.

Resolving Error E0162

To resolve this error, replace the if let expression with a let-binding. Here's the corrected version of the previous example:

struct Irrefutable(i32);
let irr = Irrefutable(0);

let Irrefutable(x) = irr;
println!("{}", x);

By using a let-binding instead of an if let expression, the error is resolved and the value of x is captured from the irrefutable pattern.


In Rust, error E0162 occurs when an irrefutable pattern is used with an if let expression. Use let-bindings when dealing with irrefutable patterns to avoid this error. It is crucial to understand the difference between refutable and irrefutable patterns when utilizing Rust's pattern matching capabilities to write expressive and flexible code.