这里生锈新手.我正在尝试打开一个文件:
let file = File::open("file.txt").unwrap();
Run Code Online (Sandbox Code Playgroud)
由于我的构建设置,它看起来像我的二进制和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
Run Code Online (Sandbox Code Playgroud)
错误消息没有说明txt必须存在的预期路径应该是什么,以便我的程序和测试看到它.如何打印此预期路径?我想打印一条消息,如:
The file "/expected/folder/file.txt" does not exist
Run Code Online (Sandbox Code Playgroud)
只是匹配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),
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
129 次 |
| 最近记录: |