rustbook

Toy programs and snippets for The Rust Programming Language book
Log | Files | Refs

main.rs (1305B)


      1 use std::fs::File;
      2 use std::io::ErrorKind;
      3 use std::io::Read;
      4 use std::io;
      5 
      6 fn main() {
      7 //    panic!("Mayday! Mayday!");
      8 //    let v = vec![1, 2, 3];
      9 //    v[99];
     10 
     11     let f = File::open("hello.txt");
     12     let f = match f {
     13         Result::Ok(file) => file,
     14         Result::Err(error) =>  match error.kind() {
     15             ErrorKind::NotFound => match File::create("hello.txt") {
     16                 Ok(fc) => fc,
     17                 Err(e) => panic!("Unable to create file: {:?}", e),
     18             },
     19             other_error => panic!("Unable to open file: {:?}", other_error),
     20         },
     21     };
     22 
     23 //    let g = File::open("gello.txt").unwrap();
     24 //    let h = File::open("yello.txt").expect("Expect lets you write your own error message");
     25 //    propagate_errors().unwrap();
     26     propagate_errors_shortstuff().unwrap();
     27 }
     28 
     29 fn propagate_errors() -> Result<String, io::Error> {
     30    let f  = File::open("not_real.txt");
     31    let mut f = match f {
     32        Ok(file) => file,
     33        Err(e) => return Err(e),
     34    };
     35 
     36     let mut s = String::new();
     37 
     38     match f.read_to_string(&mut s) {
     39         Ok(_) => Ok(s),
     40         Err(e) => Err(e),
     41     }
     42 }
     43 
     44 fn propagate_errors_shortstuff() -> Result<String, io::Error> {
     45     let mut f  = File::open("not_real.txt")?;
     46     let mut s = String::new();
     47     f.read_to_string(&mut s)?;
     48     Ok(s)
     49 }