From 0e89468188b9d347495dad5b98af137e5f477432 Mon Sep 17 00:00:00 2001 From: garhve Date: Sun, 1 Jan 2023 23:23:55 +0800 Subject: finish chapter 9 --- .../chapter-9-error-handling/result/src/main.rs | 62 ++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 rust/theBook/chapter-9-error-handling/result/src/main.rs (limited to 'rust/theBook/chapter-9-error-handling/result/src/main.rs') diff --git a/rust/theBook/chapter-9-error-handling/result/src/main.rs b/rust/theBook/chapter-9-error-handling/result/src/main.rs new file mode 100644 index 0000000..265250c --- /dev/null +++ b/rust/theBook/chapter-9-error-handling/result/src/main.rs @@ -0,0 +1,62 @@ +use std::fs::{Self,File}; +use std::io::{Self, Read, ErrorKind}; + +fn main() { + let greeting_file_result = File::open("hello.txt"); + + let greeting_file = match greeting_file_result { + Ok(file) => file, + Err(error) => match error.kind() { + ErrorKind::NotFound => match File::create("hello.txt") { + Ok(fc) => fc, + Err(e) => panic!("problem opening file {:?}",e), + }, + other_error => { + panic!("problem opening file {:?}",other_error); + } + }, + }; + + // or use unwrap, it will return value or panic just like match + // let greeting_file = File::open("hello.txt").unwrap(); +} + +// functions to read username from file +// each one is a shorter solution of its previous one. +fn read_username_from_file() -> Result { + let username_file_result = File::open("hello.txt"); + + let username_file = match username_file_result { + Ok(file) => file, + Err(e) => return Err(e), + }; + + let mut username = String::new(); + + match username_file.read_to_string(&mut username) { + Ok(_) => Ok(username), + Err(e) => Err(e), + } +} + +// ? is like match, but shorter +// return content of Ok() if true, or return Err() from whole function +fn read_username_from_file_short() -> Result { + let mut username_file = File::open("hello.txt")?; + + let mut username = String::new(); + + username_file.read_to_string(&mut username)?; + Ok(username) +} + +fn read_username_from_file_even_short() -> Result { + let mut username = String::new(); + + File::open("hello.txt")?.read_to_string(&mut username)?; + Ok(username) +} + +fn read_username_from_file_shortest() -> Result { + fs::read_to_string("hello.txt") +} -- cgit v1.2.3-70-g09d2