Concise Rust Option Iteration with While Let

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, the usage of while let in Rust is demonstrated as a more concise and efficient alternative to using match sequences when incrementing variables or iterating over Option types.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/BasicConceptsGroup(["`Basic Concepts`"]) rust(("`Rust`")) -.-> rust/DataTypesGroup(["`Data Types`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust(("`Rust`")) -.-> rust/MemorySafetyandManagementGroup(["`Memory Safety and Management`"]) rust(("`Rust`")) -.-> rust/ErrorHandlingandDebuggingGroup(["`Error Handling and Debugging`"]) rust(("`Rust`")) -.-> rust/AdvancedTopicsGroup(["`Advanced Topics`"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("`Variable Declarations`") rust/BasicConceptsGroup -.-> rust/mutable_variables("`Mutable Variables`") rust/DataTypesGroup -.-> rust/integer_types("`Integer Types`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") rust/MemorySafetyandManagementGroup -.-> rust/lifetime_specifiers("`Lifetime Specifiers`") rust/ErrorHandlingandDebuggingGroup -.-> rust/error_propagation("`Error Propagation`") rust/AdvancedTopicsGroup -.-> rust/operator_overloading("`Traits for Operator Overloading`") subgraph Lab Skills rust/variable_declarations -.-> lab-99319{{"`Concise Rust Option Iteration with While Let`"}} rust/mutable_variables -.-> lab-99319{{"`Concise Rust Option Iteration with While Let`"}} rust/integer_types -.-> lab-99319{{"`Concise Rust Option Iteration with While Let`"}} rust/function_syntax -.-> lab-99319{{"`Concise Rust Option Iteration with While Let`"}} rust/expressions_statements -.-> lab-99319{{"`Concise Rust Option Iteration with While Let`"}} rust/lifetime_specifiers -.-> lab-99319{{"`Concise Rust Option Iteration with While Let`"}} rust/error_propagation -.-> lab-99319{{"`Concise Rust Option Iteration with While Let`"}} rust/operator_overloading -.-> lab-99319{{"`Concise Rust Option Iteration with While Let`"}} end

while let

Similar to if let, while let can make awkward match sequences more tolerable. Consider the following sequence that increments i:

// Make `optional` of type `Option<i32>`
let mut optional = Some(0);

// Repeatedly try this test.
loop {
    match optional {
        // If `optional` destructures, evaluate the block.
        Some(i) => {
            if i > 9 {
                println!("Greater than 9, quit!");
                optional = None;
            } else {
                println!("`i` is `{:?}`. Try again.", i);
                optional = Some(i + 1);
            }
            // ^ Requires 3 indentations!
        },
        // Quit the loop when the destructure fails:
        _ => { break; }
        // ^ Why should this be required? There must be a better way!
    }
}

Using while let makes this sequence much nicer:

fn main() {
    // Make `optional` of type `Option<i32>`
    let mut optional = Some(0);

    // This reads: "while `let` destructures `optional` into
    // `Some(i)`, evaluate the block (`{}`). Else `break`.
    while let Some(i) = optional {
        if i > 9 {
            println!("Greater than 9, quit!");
            optional = None;
        } else {
            println!("`i` is `{:?}`. Try again.", i);
            optional = Some(i + 1);
        }
        // ^ Less rightward drift and doesn't require
        // explicitly handling the failing case.
    }
    // ^ `if let` had additional optional `else`/`else if`
    // clauses. `while let` does not have these.
}

Summary

Congratulations! You have completed the While Let lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like