Match Io ErrorKind For Recovery
Classify io failures by ErrorKind instead of string matching: fall back to defaults on NotFound, refuse on PermissionDenied, and surface anything else loudly.
Code
use std::fs;
use std::io::{self, Read};
fn read_env_file(path: &str) -> io::Result<String> {
let mut buf = String::new();
fs::File::open(path)?.read_to_string(&mut buf)?;
Ok(buf)
}
fn main() {
match read_env_file("missing.env") {
Ok(text) => println!("loaded {} bytes", text.len()),
// ErrorKind 是机器可判定的分类:不同类别走不同恢复路径
Err(e) if e.kind() == io::ErrorKind::NotFound => {
println!("no env file, using built-in defaults ({e})");
}
Err(e) if e.kind() == io::ErrorKind::PermissionDenied => {
eprintln!("refusing to continue: fix permissions ({e})");
}
Err(e) => eprintln!("unclassified io failure: {e}"),
}
// 错误本体仍留在 Result 里,kind 只影响控制流
let probe = read_env_file("missing.env");
println!(
"is not-found: {}",
matches!(probe, Err(ref e) if e.kind() == io::ErrorKind::NotFound)
);
}How it works
Match Io ErrorKind For Recovery keeps everything in the functions read_env_file and main.
Result turns the error into data — visible in the type, handled by the caller. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.
What to watch for
- The
Resultvalues will not let errors pass silently; each must be matched, unwrapped, or propagated.
Using it
Entry signature: fn read_env_file(path: &str) -> io::Result<String>
The demo output is labeled (loaded, no env file, using built-in defaults (, is not-found:), so every printed line maps back to its originating operation.
Running the file executes main, which drives read_env_file in order.
Key statements
Err(e) if e.kind() == io::ErrorKind::PermissionDenied => {
eprintln!("refusing to continue: fix permissions ({e})");
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {
println!("no env file, using built-in defaults ({e})");
}
fn read_env_file(path: &str) -> io::Result<String> {
let mut buf = String::new();
fs::File::open(path)?.read_to_string(&mut buf)?;
Ok(buf)
}
Interactive Tools for This Topic
FAQ
- Does the snippet panic on failure?
- As `Result` values — each fallible call returns one, and the caller matches or propagates it.
- What does Match Io ErrorKind For Recovery print when run?
- The script runs standalone; its 3 labeled outputs include `loaded`, `no env file, using built-in defaults (`, `is not-found:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.