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

后端 未结 1 1272
逝去的感伤
逝去的感伤 2021-01-19 17:30
fn lines_from_file(filename: F) -> Result>, io::Error>
where
    F: std::convert::AsRef

        
相关标签:
1条回答
  • 2021-01-19 18:24

    [...] 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.

    0 讨论(0)
提交回复
热议问题