在阅读书中关于错误处理的章节时,我想知道通常提到的“显式案例分析”的反面是什么。我知道并理解这个代码示例使用显式的案例分析:
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
CliError::Io(ref err) => write!(f, "IO error: {}", err),
CliError::Parse(ref err) => write!(f, "Parse error: {}", err),
}
}
但什么是隐式案例分析?
发布于 2016-10-31 14:43:25
在本书中,case analysis意味着通过直接分析enum
的每一种情况来执行计算,例如使用match
或if let
表达式。书中给出的一个极端例子是
fn file_path_ext_explicit(file_path: &str) -> Option<&str> {
match file_name(file_path) { // <-- case analysis
None => None,
Some(name) => match extension(name) { // <-- another case analysis
None => None,
Some(ext) => Some(ext),
}
}
}
显式案例分析只是指显式地使用“案例分析”。
没有“隐性案例分析”。这本书建议把常用的案例分析模式抽象成可组合的方法或宏,也许这就是你想要的。
例如,我们可以将案例分析(match
表达式)隐藏在Option<T>
上的and_then
方法中。
fn and_then<F, T, A>(option: Option<T>, f: F) -> Option<A>
where F: FnOnce(T) -> Option<A> {
match option { // <-- case analysis moved into here
None => None,
Some(value) => f(value),
}
}
然后可以将file_path_ext_explicit
函数简化为
fn file_path_ext(file_path: &str) -> Option<&str> {
// no `match` expressions
file_name(file_path).and_then(extension)
}
它更清楚地表达了该功能的意图,并且不太容易出现逻辑错误。
https://stackoverflow.com/questions/40343801
复制相似问题