Skip to content

Instantly share code, notes, and snippets.

@growvv
Created September 26, 2021 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save growvv/7556a8d56cd46854059f4691bd1fd976 to your computer and use it in GitHub Desktop.
Save growvv/7556a8d56cd46854059f4691bd1fd976 to your computer and use it in GitHub Desktop.
open a file by match or closure
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);
}
@growvv
Copy link
Author

growvv commented Sep 26, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment