Created
September 26, 2021 07:19
-
-
Save growvv/7556a8d56cd46854059f4691bd1fd976 to your computer and use it in GitHub Desktop.
open a file by match or closure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use core::panic; | |
use std::fs::File; | |
use std::io::ErrorKind; | |
fn main(){ | |
let path = "a.txt"; | |
let f = File::open(path); | |
let f = match f { | |
Ok(file) => file, | |
Err(error) => match error.kind() { | |
ErrorKind::NotFound => match File::create(path) { | |
Ok(new_file) => new_file, | |
Err(error) => panic!("create file fail: {}", error), | |
}, | |
other_error => panic!("open file fail: {:?}", other_error), | |
}, | |
}; | |
println!("{:?}", f); | |
let f = File::open(path).unwrap_or_else(|error| { | |
if error.kind() == ErrorKind::NotFound { | |
File::create(path).unwrap_or_else(|error| { | |
panic!("create file fail: {}", error); | |
}) | |
} else { | |
panic!("open file fail: {}", error); | |
} | |
}); | |
println!("{:?}", f); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ref https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html