Rust中的错误处理

Result & Panic

这次讲得详细,从错误的来历及简写过程,

都写明白了,

先浅,再深,先深,再浅,

反复之,

学习王道~

use std::fs::File;
//use std::io::ErrorKind;

fn main() {
    //panic!("crash and burn");
    //let v = vec![1, 2, 3];
    //v[99];
    /*
    let f = File::open("hello.txt");

    let f = match f {
    Ok(file) => file,
    Err(error) => match error.kind() {
        ErrorKind::NotFound => match File::create("hello.txt") {
        Ok(fc) => fc,
        Err(e) => panic!("Try create new file, but error : {:#?}", e),
        },
        other_error => panic!("There was a problem opening the file: {:#?}", other_error),
    },
    };

    let f = File::open("hello.txt").map_err(|error| {
    if error.kind() == ErrorKind::NotFound {
        File::create("hello.txt").unwrap_or_else(|error| {
        panic!("Try create new file, but error : {:#?}", error);
        })
    } else {
        panic!("There was a problem opening the file: {:#?}", error);
    }
    });
    */

    //let f = File::open("hello.txt").unwrap();
    let f = File::open("hello.txt").expect("Failed to open hello.txt");
    println!("f value is {:#?}", f);
}

猜你喜欢

转载自www.cnblogs.com/aguncn/p/11406912.html