Rust新手在这里。我正在尝试打开一个文件:
let file = File::open("file.txt").unwrap();
由于我的构建设置,看起来我的二进制文件和txt不是我期望的那样,或者我做错了所以我得到了:
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:736
错误消息没有说明txt必须存在的预期路径应该是什么,以便我的程序和测试看到它。如何打印此预期路径?我想打印一条消息:
The file "/expected/folder/file.txt" does not exist
答案 0 :(得分:5)
只需将返回的Result
明确地与所需的错误匹配,如下所示:
use std::fs::File;
use std::io::ErrorKind;
fn main() {
match File::open("file.txt") {
Ok(file) =>
println!("The file is of {} bytes", file.metadata().unwrap().len()),
Err(ref e) if e.kind() == ErrorKind::NotFound =>
println!("The file {}/file.txt does not exist", std::env::current_dir().unwrap().display()),
Err(e) =>
panic!("unexpected error: {:?}", e),
}
}