Created
May 4, 2022 20:05
-
-
Save soyart/5da13f62c0c35986222258cb42936669 to your computer and use it in GitHub Desktop.
My practice code for https://doc.rust-lang.org/book/ch09-00-error-handling.html
This file contains hidden or 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
| #![allow(dead_code)] | |
| #![allow(unused)] | |
| use std::fs::File; | |
| use std::io::{prelude::*, ErrorKind, Read, BufReader}; | |
| use std::io; | |
| fn main() { | |
| let fname = ".gitignore"; | |
| // Using expect() - panics and prints a message (no unwrapping) | |
| // let f = File::open(fname).expect(format!("failed to open file {name}", name = fname)); | |
| // Using unwrap() (unwraps result, or panics on error) | |
| let f = File::open(fname).unwrap(); | |
| // Using match(es) - more error handling logic | |
| let mut f = match File::open(fname) { | |
| Ok(fp) => fp, | |
| Err(err) => match err.kind() { | |
| ErrorKind::NotFound => { | |
| match File::create(fname) { | |
| Ok(fc) => fc, | |
| Err(err) => { | |
| panic!("difficult error: {:?}", err); | |
| } | |
| } | |
| }, | |
| _ => { | |
| panic!("difficult error: {:?}", err); | |
| } | |
| } | |
| }; | |
| // Using unwrap_or_else, which take in a closure. | |
| let mut f = File::open(fname).unwrap_or_else(|err| { | |
| if err.kind() == ErrorKind::NotFound { | |
| File::create(fname).unwrap_or_else(|err| { | |
| panic!("not found and can't create: {:?}", err); | |
| }) | |
| } else { | |
| panic!("unknown error {:?}", err); | |
| } | |
| }); | |
| let fcontent = read_string_file(&mut f).unwrap(); | |
| println!("{}", fcontent); | |
| let reader = BufReader::new(File::open(fname).unwrap()); | |
| for line in reader.lines() { | |
| let s = match line { | |
| Ok(l) => l, | |
| Err(_) => { | |
| panic!("wtf read_line failed") | |
| }, | |
| }; | |
| println!("{}", s) | |
| } | |
| } | |
| // read_string_file returns either Result<String, io::Error> | |
| fn read_string_file(fp: &mut File) -> Result<String, io::Error> { | |
| let mut fbuf = String::new(); | |
| match fp.read_to_string(&mut fbuf) { | |
| Ok(_) => Ok(fbuf), | |
| Err(e) => Err(e), | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment