使用 While Let 实现 Rust 简洁的 Option 迭代

RustRustBeginner
立即练习

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

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,展示了 Rust 中 while let 的用法,它是在递增变量或遍历 Option 类型时使用 match 序列的一种更简洁高效的替代方法。

注意:如果实验未指定文件名,你可以使用任何你想要的文件名。例如,你可以使用 main.rs,通过 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{{"使用 While Let 实现 Rust 简洁的 Option 迭代"}} rust/mutable_variables -.-> lab-99319{{"使用 While Let 实现 Rust 简洁的 Option 迭代"}} rust/integer_types -.-> lab-99319{{"使用 While Let 实现 Rust 简洁的 Option 迭代"}} rust/function_syntax -.-> lab-99319{{"使用 While Let 实现 Rust 简洁的 Option 迭代"}} rust/expressions_statements -.-> lab-99319{{"使用 While Let 实现 Rust 简洁的 Option 迭代"}} rust/lifetime_specifiers -.-> lab-99319{{"使用 While Let 实现 Rust 简洁的 Option 迭代"}} rust/error_propagation -.-> lab-99319{{"使用 While Let 实现 Rust 简洁的 Option 迭代"}} rust/operator_overloading -.-> lab-99319{{"使用 While Let 实现 Rust 简洁的 Option 迭代"}} end

while let

if let 类似,while let 可以让那些笨拙的 match 序列更易于接受。考虑以下递增 i 的序列:

// 创建一个类型为 `Option<i32>` 的 `optional`
let mut optional = Some(0);

// 重复进行此测试。
loop {
    match optional {
        // 如果 `optional` 解构成功,执行块中的代码。
        Some(i) => {
            if i > 9 {
                println!("大于 9,退出!");
                optional = None;
            } else {
                println!("`i` 的值是 `{:?}`。再试一次。", i);
                optional = Some(i + 1);
            }
            // ^ 需要 3 个缩进!
        },
        // 当解构失败时退出循环:
        _ => { break; }
        // ^ 为什么需要这样?肯定有更好的方法!
    }
}

使用 while let 会使这个序列好得多:

fn main() {
    // 创建一个类型为 `Option<i32>` 的 `optional`
    let mut optional = Some(0);

    // 这可以理解为:“当 `let` 将 `optional` 解构为
    // `Some(i)` 时,执行块 (`{}`)。否则 `break`。
    while let Some(i) = optional {
        if i > 9 {
            println!("大于 9,退出!");
            optional = None;
        } else {
            println!("`i` 的值是 `{:?}`。再试一次。", i);
            optional = Some(i + 1);
        }
        // ^ 向右的缩进更少,并且不需要
        // 显式处理失败的情况。
    }
    // ^ `if let` 有额外的可选 `else`/`else if`
    // 子句。`while let` 没有这些。
}

总结

恭喜你!你已经完成了 While Let 实验。你可以在 LabEx 中练习更多实验来提升你的技能。