study_example/error_handle/
result_recorverable.rs

1use std::fs::File;
2use std::io::{self, ErrorKind, Read};
3
4fn open_file(file_path: &str) -> File {
5    /*
6    File::open 的返回类型是 Result<T, E> 。
7    通用参数 T 已由 File::open 的实现填充为成功值的类型 std::fs::File ,它是一个文件句柄。
8    错误值中使用的 E 类型为 std::io::Error 。
9    此返回类型意味着对 File::open 的调用可能会成功并返回我们可以读取或写入的文件句柄。
10    函数调用也可能失败:例如,文件可能不存在,或者我们可能没有访问该文件的权限。
11    File::open 函数需要有一种方法来告诉我们它是成功还是失败,同时为我们提供文件句柄或错误信息。
12    此信息正是 Result 枚举所传达的信息
13    */
14    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).unwrap();
31    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    /*let mut open_file = File::open(file_path)?;
52    open_file.read_to_string(&mut content)?;*/
53    // 可以简化为如下
54    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}