在 Rust 中使用提前返回处理错误

RustRustBeginner
立即练习

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

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

简介

在本实验中,我们探讨提前返回(early returns)的概念,将其作为在Rust中处理错误的一种方式。示例代码展示了如何使用 match 语句和提前返回优雅地处理错误,使代码更易于读写。我们还讨论了显式错误处理的局限性,并介绍了在需要解包值而又不引发恐慌(panic)的情况下使用 ? 运算符。

注意:如果实验未指定文件名,你可以使用任何你想要的文件名。例如,你可以使用 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/AdvancedTopicsGroup(["Advanced Topics"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("Variable Declarations") rust/DataTypesGroup -.-> rust/integer_types("Integer Types") rust/DataTypesGroup -.-> rust/string_type("String Type") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("Function Syntax") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("Expressions and Statements") rust/AdvancedTopicsGroup -.-> rust/operator_overloading("Traits for Operator Overloading") subgraph Lab Skills rust/variable_declarations -.-> lab-99242{{"在 Rust 中使用提前返回处理错误"}} rust/integer_types -.-> lab-99242{{"在 Rust 中使用提前返回处理错误"}} rust/string_type -.-> lab-99242{{"在 Rust 中使用提前返回处理错误"}} rust/function_syntax -.-> lab-99242{{"在 Rust 中使用提前返回处理错误"}} rust/expressions_statements -.-> lab-99242{{"在 Rust 中使用提前返回处理错误"}} rust/operator_overloading -.-> lab-99242{{"在 Rust 中使用提前返回处理错误"}} end

提前返回

在上一个示例中,我们使用组合器显式地处理了错误。处理这种情况分析的另一种方法是结合使用 match 语句和提前返回

也就是说,如果发生错误,我们可以简单地停止执行函数并返回错误。对于某些人来说,这种形式的代码可能更易于读写。考虑使用提前返回重写的上一个示例的这个版本:

use std::num::ParseIntError;

fn multiply(first_number_str: &str, second_number_str: &str) -> Result<i32, ParseIntError> {
    let first_number = match first_number_str.parse::<i32>() {
        Ok(first_number)  => first_number,
        Err(e) => return Err(e),
    };

    let second_number = match second_number_str.parse::<i32>() {
        Ok(second_number)  => second_number,
        Err(e) => return Err(e),
    };

    Ok(first_number * second_number)
}

fn print(result: Result<i32, ParseIntError>) {
    match result {
        Ok(n)  => println!("n is {}", n),
        Err(e) => println!("Error: {}", e),
    }
}

fn main() {
    print(multiply("10", "2"));
    print(multiply("t", "2"));
}

至此,我们已经学会了使用组合器和提前返回显式地处理错误。虽然我们通常希望避免恐慌,但显式地处理所有错误很麻烦。

在下一节中,我们将介绍 ? 运算符,用于在我们只需要 unwrap 而又不会引发 panic 的情况下。

总结

恭喜你!你已经完成了“提前返回”实验。你可以在LabEx中练习更多实验来提升你的技能。