实现说明
io::Error::other 装箱自定义失败以函数 parse_port、classify、main为骨架。
Result 把错误变成数据——类型里可见,由调用方处理。match 把每种情况写明白;漏写一个就编译不过。
使用要点
?运算符是承重墙:删掉一个,错误处理就变成你的事。- 直接运行文件,输出会带上标签,比如
message:、classification:、missing file kind is NotFound:——输出的每一行都能指回产生它的那次调用。 main按顺序串起parse_port、classify;运行文件就会把这个流程跑一遍。
常见问题
调用方该如何处理失败?
没有 panic——Result 携带失败。
运行「io::Error::other 装箱自定义失败」会打印什么?
运行文件本身,message:、classification:、missing file kind is NotFound: 这些前缀各对应一段演示逻辑。
入口签名:fn parse_port(raw: &str) -> std::io::Result<u16>
核心语句
let missing = std::fs::read("definitely-missing.txt").unwrap_err();
fn parse_port(raw: &str) -> std::io::Result<u16> {
raw.trim().parse::<u16>().map_err(|e| {
// Error::other 把任意错误装箱成 io::Error(1.74 起取代 new(ErrorKind::Other, ..))
Error::other(format!("invalid port {:?}: {}", raw, e))
})
}
let err = parse_port("99999").unwrap_err();
代码示例
use std::io::{Error, ErrorKind};
fn parse_port(raw: &str) -> std::io::Result<u16> {
raw.trim().parse::<u16>().map_err(|e| {
// Error::other 把任意错误装箱成 io::Error(1.74 起取代 new(ErrorKind::Other, ..))
Error::other(format!("invalid port {:?}: {}", raw, e))
})
}
fn classify(err: &Error) -> &'static str {
// boxed custom failures and real IO errors share one ErrorKind match
match err.kind() {
ErrorKind::InvalidInput => "input rejected",
ErrorKind::NotFound => "resource missing",
_ => "unclassified failure",
}
}
fn main() {
let err = parse_port("99999").unwrap_err();
println!("message: {}", err);
println!("classification: {}", classify(&err));
// 真实 IO 错误的 kind 可直接匹配:打开不存在的文件得到 NotFound
let missing = std::fs::read("definitely-missing.txt").unwrap_err();
println!("missing file kind is NotFound: {}", missing.kind() == ErrorKind::NotFound);
}