1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| use std::error::Error; use std::io::ErrorKind; use std::fs::File; use std::io::Read; use std::net::IpAddr; use std::io;
fn main() -> Result<(), Box<dyn Error>> {
let f = File::open("hello.txt"); match f { Ok(file) => file, Err(error) => panic!("Problem opening the file: {:?}", error), };
let _f = File::open("hello.txt").unwrap();
let _f = File::open("hello.txt").expect("Failed to open hello.txt");
let f = File::open("hello.txt"); let _f = match f { Ok(file) => file, Err(error) => match error.kind() { ErrorKind::NotFound => match File::create("hello.txt") { Ok(fc) => fc, Err(error) => panic!("Problem creating the file: {:?}", error), }, other_error => panic!("Problem opening the file: {:?}", other_error), }, };
let _f = File::open("hello.txt").unwrap_or_else(|error| { if error.kind() == ErrorKind::NotFound { File::create("hello.txt").unwrap_or_else(|error| { panic!("Problem creating the file: {:?}", error); }) } else { panic!("Problem opening the file: {:?}", error); } });
let _ = read_username_from_file();
let _ = _read_username_from_file();
let _home: IpAddr = "127.0.0.1" .parse() .expect("Hardcoded IP address should be valid");
let guess = Guess::new(99); println!("Guess value: {}", guess.value());
let _greeting_file = File::open("hello.txt")?; Ok(()) }
fn read_username_from_file() -> Result<String, io::Error> { let f = File::open("hello.txt"); let mut f = match f { Ok(file) => file, Err(e) => return Err(e), };
let mut s = String::new();
match f.read_to_string(&mut s) { Ok(_) => Ok(s), Err(e) => Err(e), } }
pub struct Guess { value: i32, }
impl Guess { pub fn new(value: i32) -> Guess { if value < 1 || value > 100 { panic!("Guess value must be between 1 and 100, got {}.", value); }
Guess { value } }
pub fn value(&self) -> i32 { self.value } }
fn _read_username_from_file() -> Result<String, io::Error> { let mut f = File::open("hello.txt")?; let mut s = String::new(); f.read_to_string(&mut s)?; Ok(s) }
|