Rust Error Handling

Result & Panic

This put it in detail, from the mistakes of history and abbreviated process,

They are written to understand,

First shallow, then deep, deep first, then shallow,

Again, the

Learn benevolent ~

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

Guess you like

Origin www.cnblogs.com/aguncn/p/11406912.html