Rust 演算子によるエラーハンドリングの簡略化

RustRustBeginner
今すぐ練習

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

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、結果をチェーン化する際にコードをクリーンにする方法として ? 演算子が導入されます。これは Result を返す式の末尾で使用され、ErrOk のブランチを自動的に処理することでコードを簡略化します。提供された例では、Rust で ? 演算子を使用してさまざまな数学演算とその潜在的なエラーを処理する方法を示しています。

注: 実験でファイル名が指定されていない場合、好きなファイル名を使用できます。たとえば、main.rs を使用して、rustc main.rs &&./main でコンパイルして実行できます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("Rust")) -.-> rust/AdvancedTopicsGroup(["Advanced Topics"]) rust(("Rust")) -.-> rust/BasicConceptsGroup(["Basic Concepts"]) rust(("Rust")) -.-> rust/DataTypesGroup(["Data Types"]) rust(("Rust")) -.-> rust/FunctionsandClosuresGroup(["Functions and Closures"]) rust(("Rust")) -.-> rust/DataStructuresandEnumsGroup(["Data Structures and Enums"]) rust(("Rust")) -.-> rust/ErrorHandlingandDebuggingGroup(["Error Handling and Debugging"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("Variable Declarations") rust/DataTypesGroup -.-> rust/floating_types("Floating-point Types") rust/DataTypesGroup -.-> rust/string_type("String Type") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("Function Syntax") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("Expressions and Statements") rust/DataStructuresandEnumsGroup -.-> rust/method_syntax("Method Syntax") rust/ErrorHandlingandDebuggingGroup -.-> rust/panic_usage("panic! Usage") rust/AdvancedTopicsGroup -.-> rust/operator_overloading("Traits for Operator Overloading") subgraph Lab Skills rust/variable_declarations -.-> lab-150172{{"Rust 演算子によるエラーハンドリングの簡略化"}} rust/floating_types -.-> lab-150172{{"Rust 演算子によるエラーハンドリングの簡略化"}} rust/string_type -.-> lab-150172{{"Rust 演算子によるエラーハンドリングの簡略化"}} rust/function_syntax -.-> lab-150172{{"Rust 演算子によるエラーハンドリングの簡略化"}} rust/expressions_statements -.-> lab-150172{{"Rust 演算子によるエラーハンドリングの簡略化"}} rust/method_syntax -.-> lab-150172{{"Rust 演算子によるエラーハンドリングの簡略化"}} rust/panic_usage -.-> lab-150172{{"Rust 演算子によるエラーハンドリングの簡略化"}} rust/operator_overloading -.-> lab-150172{{"Rust 演算子によるエラーハンドリングの簡略化"}} end

?

match を使って結果をチェーン化するとかなり汚くなります。幸いにも、? 演算子を使うことでもう一度きれいにすることができます。?Result を返す式の末尾で使用され、match 式に相当します。ここで、Err(err) ブランチは早期の return Err(From::from(err)) に展開され、Ok(ok) ブランチは ok 式に展開されます。

mod checked {
    #[derive(Debug)]
    enum MathError {
        DivisionByZero,
        NonPositiveLogarithm,
        NegativeSquareRoot,
    }

    type MathResult = Result<f64, MathError>;

    fn div(x: f64, y: f64) -> MathResult {
        if y == 0.0 {
            Err(MathError::DivisionByZero)
        } else {
            Ok(x / y)
        }
    }

    fn sqrt(x: f64) -> MathResult {
        if x < 0.0 {
            Err(MathError::NegativeSquareRoot)
        } else {
            Ok(x.sqrt())
        }
    }

    fn ln(x: f64) -> MathResult {
        if x <= 0.0 {
            Err(MathError::NonPositiveLogarithm)
        } else {
            Ok(x.ln())
        }
    }

    // 中間関数
    fn op_(x: f64, y: f64) -> MathResult {
        // `div` が「失敗」した場合、`DivisionByZero` が `return` されます
        let ratio = div(x, y)?;

        // `ln` が「失敗」した場合、`NonPositiveLogarithm` が `return` されます
        let ln = ln(ratio)?;

        sqrt(ln)
    }

    pub fn op(x: f64, y: f64) {
        match op_(x, y) {
            Err(why) => panic!("{}", match why {
                MathError::NonPositiveLogarithm
                    => "logarithm of non-positive number",
                MathError::DivisionByZero
                    => "division by zero",
                MathError::NegativeSquareRoot
                    => "square root of negative number",
            }),
            Ok(value) => println!("{}", value),
        }
    }
}

fn main() {
    checked::op(1.0, 10.0);
}

Result をマッピング/合成する方法はたくさんあるので、ドキュメントを確認することを忘れないでください。

まとめ

おめでとうございます!あなたは ? の実験を完了しました。あなたの技術を向上させるために、LabEx でさらに多くの実験を練習できます。