use std::fs::File;use std::io::ErrorKind;fnmain() {let f =File::open("hello.txt").map_err(|error| {if error.kind() == ErrorKind::NotFound { File::create("hello.txt").unwrap_or_else(|error| {panic!("Tried to create file but there was a problem: {:?}", error); }) } else {panic!("There was a problem opening the file: {:?}", error); } });}
2.2 unwrap and expect
Result<T, E>类型定义了很多方法处理各种情况,可以使用unwrap方法得到其成员值。
use std::fs::File;fnmain() {let f =File::open("hello.txt").unwrap();}thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value:Error {repr:Os { code:2, message:"No such file or directory" } }',src/libcore/result.rs:906:4
use std::io;use std::io::Read;use std::fs::File;fnread_username_from_file() ->Result<String, io::Error> {letmut f =File::open("hello.txt")?;letmut s =String::new(); f.read_to_string(&mut s)?;Ok(s)}