Rust中的错误处理

我的未来我决定 提交于 2019-11-28 12:16:00

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);
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!