https://zhuanlan.zhihu.com/p/109242831
fn main() { let path = "/tmp/dat"; println!("{}", read_file(path)); } fn read_file(path: &str) -> String { std::fs::read_to_string(path).unwrap() }
Compiling hello_world v0.1.0 (/data2/rust/unwrap) Finished dev [unoptimized + debuginfo] target(s) in 0.47s [root@bogon unwrap]# cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.01s Running `target/debug/hello_world` thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: Os { code: 2, kind: NotFound, message: "No such file or directory" }', src/main.rs:7:43 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
fn main() { let path = "/tmp/dat"; //文件路径 match read_file(path) { //判断方法结果 Ok(file) => { println!("{}", file) } //OK 代表读取到文件内容,正确打印文件内容 Err(e) => { println!("{} {}", path, e) } //Err代表结果不存在,打印错误结果 } } fn read_file(path: &str) -> Result<String,std::io::Error> { //Result作为结果返回值 std::fs::read_to_string(path) //读取文件内容 }
[root@bogon unwrap2]# cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.01s Running `target/debug/hello_world` /tmp/dat No such file or directory (os error 2)
[root@bogon unwrap2]# touch /tmp/dat [root@bogon unwrap2]# cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.01s Running `target/debug/hello_world` [root@bogon unwrap2]# echo 'test unwrap' >> /tmp/dat [root@bogon unwrap2]# cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.01s Running `target/debug/hello_world` test unwrap [root@bogon unwrap2]#