|
| 1 | +//! Example of the new operator `?` added in Rust-1.13.0. |
| 2 | +//! See https://blog.rust-lang.org/2016/11/10/Rust-1.13.html |
| 3 | +
|
| 4 | +use std::io::prelude::*; |
| 5 | +use std::fs::File; |
| 6 | +use std::io; |
| 7 | + |
| 8 | +fn read_username_from_file() -> Result<String, io::Error> { |
| 9 | + let mut f = File::open("data/username.txt")?; |
| 10 | + let mut s = String::new(); |
| 11 | + |
| 12 | + f.read_to_string(&mut s)?; |
| 13 | + |
| 14 | + Ok(s) |
| 15 | +} |
| 16 | + |
| 17 | +fn read_username_from_file_with_matches() -> Result<String, io::Error> { |
| 18 | + let f = File::open("data/username.txt"); |
| 19 | + let mut f = match f { |
| 20 | + Ok(file) => file, |
| 21 | + Err(e) => return Err(e), |
| 22 | + }; |
| 23 | + |
| 24 | + let mut s = String::new(); |
| 25 | + match f.read_to_string(&mut s) { |
| 26 | + Ok(_) => Ok(s), |
| 27 | + Err(e) => Err(e), |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +fn read_username_from_file_with_try() -> Result<String, io::Error> { |
| 32 | + let mut f = try!(File::open("data/username.txt")); |
| 33 | + let mut s = String::new(); |
| 34 | + |
| 35 | + try!(f.read_to_string(&mut s)); |
| 36 | + |
| 37 | + Ok(s) |
| 38 | +} |
| 39 | + |
| 40 | +#[cfg(test)] |
| 41 | +mod tests { |
| 42 | + #[test] |
| 43 | + fn question_mark() { |
| 44 | + let found = ::read_username_from_file(); |
| 45 | + assert!(!found.is_err()); |
| 46 | + assert_eq!(found.unwrap(), "eliovir\n".to_string()); |
| 47 | + } |
| 48 | + #[test] |
| 49 | + fn with_matches() { |
| 50 | + let found = ::read_username_from_file_with_matches(); |
| 51 | + assert!(!found.is_err()); |
| 52 | + assert_eq!(found.unwrap(), "eliovir\n".to_string()); |
| 53 | + } |
| 54 | + #[test] |
| 55 | + fn with_try() { |
| 56 | + let found = ::read_username_from_file_with_try(); |
| 57 | + assert!(!found.is_err()); |
| 58 | + assert_eq!(found.unwrap(), "eliovir\n".to_string()); |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +fn main() { |
| 63 | + match read_username_from_file() { |
| 64 | + Ok(s) => println!("The file `data/username.txt` contains `{}`.", s), |
| 65 | + Err(e) => println!("Something went wrong: {}", e), |
| 66 | + }; |
| 67 | + |
| 68 | + match read_username_from_file_with_matches() { |
| 69 | + Ok(s) => println!("The file `data/username.txt` contains `{}`.", s), |
| 70 | + Err(e) => println!("Something went wrong: {}", e), |
| 71 | + }; |
| 72 | + |
| 73 | + match read_username_from_file_with_try() { |
| 74 | + Ok(s) => println!("The file `data/username.txt` contains `{}`.", s), |
| 75 | + Err(e) => println!("Something went wrong: {}", e), |
| 76 | + }; |
| 77 | +} |
0 commit comments