0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RustのResult型のエラーハンドリング

0
Last updated at Posted at 2021-10-31

パターンマッチを使う方法

fn main() {
    let result: Result<i32, String> = Ok(200);
    let int = match result {
        Ok(int) => int,
        Err(code) => panic!("Error! code: {}", code)
    };
    println!("Success! int: {}", int);

    let result: Result<i32, String> = Err(500.to_string());
    let int = match result {
        Ok(int) => int,
        Err(code) => panic!("Error! code: {}", code)
    };
    println!("Success! int: {}", int);
}
// Success! int: 200
// thread 'main' panicked at 'Error! code: 500', src/main.rs:***/***

わかりやすいけど、ネストが深くなりがち。

unwrap_or_elseを使った方法

fn main() {
    let result: Result<i32, String> = Ok(200);
    let int = result.unwrap_or_else(|e| panic!("Error! code: {}", e));
    println!("Success! int: {}", int);

    let result: Result<i32, String> = Err(500.to_string());
    let int = result.unwrap_or_else(|e| panic!("Error! code: {}", e));
    println!("Success! int: {}", int);
}

// Success! int: 200
// thread 'main' panicked at 'Error! code: 500', src/main.rs:***:**

これでいい感じに書ける。

他にもunwrap_or とかexpect とかあるけど、unwrap_or_elseが使いやすそう。

参考

バージョン情報

$ cargo --version
cargo 1.54.0 (5ae8d74b3 2021-06-22)

$ rustc -V                                                                                                                                                                 
rustc 1.54.0 (a178d0322 2021-07-26)

$ rustup -V                                                                                                                                                                
rustup 1.24.3 (ce5817a94 2021-05-31)
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?