20
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),
    }
}

I'd like to use this instead:

if let lines = Ok(lines_from_file(filename)) {
    for line in lines {
        println!("{:?}", line);
    }
} else {
    println!("Error {:?}" /*what goes here?*/,)
}

But that gives an error:

| if let lines = Ok(lines_from_file(filename)) {
|                ^^ cannot infer type for `E`

What is the idiomatic way of using an if-let binding when matching a Result and still being able to capture the error?

0

1 Answer 1

31

[...] using an if-let binding when matching a Result and still being able to capture the error?

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?

Regarding your compiler error: you added the Ok() on the wrong side:

if let Ok(lines) = lines_from_file(filename) { ... }

This is the correct way of using if let: the destructuring pattern to the left, the expression producing a value to the right.

5
  • Ok so if let Ok(lines) = lines_from_file(filename) {...} else { println!("Error"); } would be a reasonable approach.
    – Delta_Fore
    Nov 12, 2017 at 12:36
  • 7
    @Ronnie It would work, but of course, you wouldn't print any information about the error. So I'd recommend you to just use match like in your first example. Nov 12, 2017 at 12:41
  • Is there an opposite pattern? I generally want to leave error handling nested in the beginning and then proceed knowing that the value is what I expect it to be
    – radrow
    Jun 28 at 16:44
  • @radrow Not 100% sure what you mean, but you can do if let Err(e) = ... for sure. Or use let Ok(v) = returnsResult() else { /* diverging expr */ } (let else). Jun 28 at 17:43
  • Perfect, I needed that let-else construction exactly. Thanks!
    – radrow
    Jun 28 at 18:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.