If-Let Statements

The need for all match statements in Rust to be completely exhaustive for all possible matches can, in some cases, lead to boilerplate code that may be annoying to write.

For situations where pattern matching is being used on a value, and not all matches need to be considered when checking that value, if-let statements will likely be better suited for the task.

An if-let statement is a control flow statement that defines a single matching pattern and then checks whether or not a given variable matches it:

The above example is similar to the first example given for match statements on the previous page, with the exception that this is exclusively checking if the variable num exactly matches the value 5, and for no other matching pattern.


    

If-let statements can, of course, work with discriminants in enums as well. The below example is a modified example regarding enums from the previous page:


    

Exercise:
Try defining an enum of your own with variants of one type (tuples, structs or units), then write an if-let statement to match on one of these variants:


    

Regarding enum structs (discriminants of an enum defined as structs), the primary way to access or edit their fields is through pattern matching:

Temporary bindings are made to successful matches, which can then be accessed and edited. In the above example, the aliases match_x through to match_z represent these bindings.


    

Additionally, when matching on enum structs, some of the fields being matched on can be optionally omitted with range syntax (double full stop) if they are irrelevant to the desired match: