Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

早期リターン

前の例では、コンビネータを使ってエラーを明示的に処理しました。 この場合分けに対処するもう 1 つの方法は、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"));
}

ここまでで、コンビネータと早期リターンを使ってエラーを明示的に 処理する方法を学びました。一般的にはパニックを避けたい一方で、 すべてのエラーを明示的に処理するのは面倒です。

次のセクションでは、panic を引き起こす可能性なしに単に unwrap する必要がある場合のために、? を紹介します。