【Rust】Result

Resultは、失敗するかもしれない処理の結果を表現する列挙型。

enum Result<T, E>{
    Ok(T),
    Err(E),
}
fn get_value_bad(v: bool, result: &mut usize) -> usize {
    if v {
        *result = 100;
        true
    } else {
        false
    }
}

fn get_value_good(v: bool) -> Result<usize, &'static str> {
    if v {
        OK(100)
    } else {
        Err("error message")
    }
}

fn main(){
    let mut result = 0;
    if get_value_bad(true, &mut result){
        println!("success: {}", result);
    } else {
        println!("failure");
    }

    match get_value_good(true){
        Ok(result) => println!("success: {}", result),
        Err(msg) => println!("failure")
    }
}
fn plus_one(x: Option<i32>) -> Option<i32> {
    match x {
        None => None,
        Some(i) => Some(i + 1),
    }
}

fn main(){
    let five = Some(5);
    let six = plus_one(five);
    let none = plus_one(None);
}
use std::fs::File;

fn main(){
    let f = File::open("hello.txt");

    let _f = match f {
        Ok(file) => file,
        Err(error) => {
            panic!("There was a problem opening the file: {:?}", error);
        }
    };
}

OptionはSome, None, ResultはOk, Errで共にエラーハンドリングなどで使うのね。