在《铁 rust 》中,我有一个枚举MatchType
enum MatchType {
Exact,
Lower,
Greater,
Other,
}
我在我的compare
函数中使用它来比较两个String
.如果MatchType
是Exact/Lower/Greater
,我想将String
转换为f64
并比较它们的值(如果parse
失败,我认为比较结果是false
).
我可以通过一些样板代码轻松实现这一点,如下所示:
fn compare(str_one: String, str_two: String, match_type: MatchType) -> bool {
match match_type {
MatchType::Exact => {
let f_one = str_one.parse::<f64>();
let f_two = str_two.parse::<f64>();
if let (Ok(f_one), Ok(f_two)) = (f_one, f_two) {
f_one == f_two
} else {
false
}
},
MatchType::Lower => {
let f_one = str_one.parse::<f64>();
let f_two = str_two.parse::<f64>();
if let (Ok(f_one), Ok(f_two)) = (f_one, f_two) {
f_one < f_two
} else {
false
}
},
MatchType::Greater => {
let f_one = str_one.parse::<f64>();
let f_two = str_two.parse::<f64>();
if let (Ok(f_one), Ok(f_two)) = (f_one, f_two) {
f_one > f_two
} else {
false
}
},
MatchType::Other => false,
}
}
但我想try 更简洁的方法:首先判断匹配项是否为这三个Exact/Lower/Greater
之一,然后解析字符串,然后执行实际比较,如下所示:
fn compare(str_one: String, str_two: String, match_type: MatchType) -> bool {
match match_type {
MatchType::Exact | MatchType::Lower | MatchType::Greater => {
let f_one = str_one.parse::<f64>();
let f_two = str_two.parse::<f64>();
if let (Ok(f_one), Ok(f_two)) = (f_one, f_two) {
match match_type {
MatchType::Exact => f_one == f_two,
MatchType::Lower => f_one < f_two,
MatchType::Greater => f_one > f_two,
// --- Non-exhaustive ---
_ => false,
}
} else {
false
}
},
MatchType::Other => false,
}
}
它可以工作,但内部匹配不是完全的,当然简单的_ => false
可以修复它,但我想知道我是否可以以某种方式告诉Rust编译器,内部模式只是这3个枚举变体Lower/Greater/Exact
.
我试着这样用pattern binding:
fn compare(str_one: String, str_two: String, match_type: MatchType) -> bool {
match match_type {
float_match @ (MatchType::Exact | MatchType::Lower | MatchType::Greater) => {
let f_one = str_one.parse::<f64>();
let f_two = str_two.parse::<f64>();
if let (Ok(f_one), Ok(f_two)) = (f_one, f_two) {
match float_match {
MatchType::Exact => f_one == f_two,
MatchType::Lower => f_one < f_two,
MatchType::Greater => f_one > f_two,
// --- Non-exhaustive error here ---
}
} else {
false
}
},
MatchType::Other => false,
}
}
但我还是得到了non-exhaustive
个错误.有什么办法处理这件事吗?