Gre*_*een 6 error-handling pattern-matching rust
在 Rust 中,我想删除一个文件。文档告诉我,fs::remove_file如果文件是目录、不存在或用户缺乏该操作的权限,则会返回错误。
现在,在我的场景中,我想区分这三种情况。但是,我的调试器不会显示错误的类型,println!结果只是打印错误消息。
那么,我如何区分这些情况呢?
use std::fs;
fn rem(path: &str) {
let msg = match fs::remove_file(path) {
Ok(()) => "is fine",
Err(NotExist) => "does not exist", // TODO: Pattern
Err(IsDir) => "is a directory", // TODO: Pattern
Err(_) => "is not yours",
};
println!("The file {}!", msg);
}
fn main() {
rem("/tmp/this-file-hopefully-not-exists.xyz"); // print "not exist"
rem("/tmp/this-is-a-directory"); // prints "is a directory"
rem("/tmp/this-file-belongs-to-root.xyz"); // prints "is not yours"
}
Run Code Online (Sandbox Code Playgroud)
std::fs::remove_file返回 a std::io::Result<()>,它只是 的别名Result<(), std::io::Error>。
因此,您可以匹配它来提取错误消息的类型。特别是,您可能想要查看.kind()错误的原因:
fn rem(path: &str) {
use std::io::ErrorKind;
let message = match std::fs::remove_file(path) {
Ok(()) => "ok",
Err(e) if e.kind() == ErrorKind::NotFound => "not found",
Err(e) if e.kind() == ErrorKind::IsADirectory => "is a directory",
Err(e) => "other",
}
println!("{message}");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
793 次 |
| 最近记录: |