study_example/error_handle/
result_recorverable.rs1use std::fs::File;
2use std::io::{self, ErrorKind, Read};
3
4fn open_file(file_path: &str) -> File {
5 let open_file_result = File::open(file_path);
15 match open_file_result {
16 Ok(file) => file,
17 Err(e) => match e.kind() {
18 ErrorKind::NotFound => match File::create(file_path) {
19 Ok(fc) => fc,
20 Err(error_create) => panic!("create file error: {:?}", error_create),
21 },
22 other_error => {
23 panic!("Open file error: {:?}", other_error);
24 }
25 },
26 }
27}
28
29fn open_file_unwrap(file_path: &str) -> File {
30 let file = File::open(file_path).expect("file not exist.");
32 println!("file: {:?}", file);
33 return file;
34}
35
36fn read_file_from_name(file_path: &str) -> Result<String, io::Error> {
37 let open_file_result = File::open(file_path);
38 let mut file = match open_file_result {
39 Ok(file) => file,
40 Err(e) => return Err(e),
41 };
42 let mut content = String::new();
43 match file.read_to_string(&mut content) {
44 Ok(_) => Ok(content),
45 Err(e) => return Err(e),
46 }
47}
48
49fn read_file_from_name_short(file_path: &str) -> Result<String, io::Error> {
50 let mut content = String::new();
51 File::open(file_path)?.read_to_string(&mut content)?;
55 return Ok(content);
56}
57
58pub fn result_recover_study() {
59 let file_path = String::from("hello.txt");
60 open_file(&file_path);
61 open_file_unwrap(&file_path);
62 let file_content = read_file_from_name(&file_path).expect("read file error.");
63 println!("file content: {}", file_content);
64 let file_content2 = read_file_from_name_short(&file_path).expect("read file short error.");
65 println!("file content2: {}", file_content2);
66}