在匹配“Result"并且仍然能够捕获错误时使用 if-let 绑定的惯用方法是什么? [英] What is the idiomatic way of using an if-let binding when matching a `Result` and still being able to capture the error?
问题描述
fn lines_from_file<F>(filename: F) -> Result<io::Lines<BufReader<File>>, io::Error>
where
F: std::convert::AsRef<std::path::Path>,
{
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
fn main() {
let filename: &str = "input.pdl";
// This works fine
match lines_from_file(filename) {
Ok(lines) => {
for line in lines {
println!("{:?}", line);
},
}
Err(e) => println!("Error {:?}", e),
}
}
我想改用这个:
if let lines = Ok(lines_from_file(filename)) {
for line in lines {
println!("{:?}", line);
}
} else {
println!("Error {:?}" /*what goes here?*/,)
}
但这会导致错误:
| if let lines = Ok(lines_from_file(filename)) {
| ^^ cannot infer type for `E`
在匹配 Result
并且仍然能够捕获错误时使用 if-let 绑定的惯用方法是什么?
What is the idiomatic way of using an if-let binding when matching a Result
and still being able to capture the error?
推荐答案
[...] 在匹配结果时使用 if-let 绑定并且仍然能够捕获错误?
[...] using an if-let binding when matching a Result and still being able to capture the error?
对于一个if let
,这从根本上是不可能的.if let
构造的唯一目的是在您只想解构一种模式的情况下使生活更轻松.如果你想解构 Result
的两种情况,你必须使用 match
(或多个 if let
或 unwrap()
,但这不是一个好的解决方案).为什么你不想首先使用 match
?
This is fundamentally impossible with one if let
. The if let
construct's only purpose is to make life easier in the case where you only want to destructure one pattern. If you want to destructure both cases of a Result
, you have to use match
(or multiple if let
or unwrap()
, but this is not a good solution). Why you don't want to use match
in the first place?
关于您的编译器错误:您在错误的一侧添加了 Ok()
:
Regarding your compiler error: you added the Ok()
on the wrong side:
if let Ok(lines) = lines_from_file(filename) { ... }
这是使用 if let
的正确方法:左边的解构模式,右边的表达式产生一个值.
This is the correct way of using if let
: the destructuring pattern to the left, the expression producing a value to the right.
这篇关于在匹配“Result"并且仍然能够捕获错误时使用 if-let 绑定的惯用方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!