Map_err does not work like match

Like as below, I think fn ng and fn ok should do the same thing.
But, I am wrong. What is the difference between them?

playground

use std::num::ParseIntError;

fn value(x: &str) -> Result<i32, ParseIntError> {
    x.parse()
}

fn ng() -> Result<i32, Box<dyn std::error::Error>> {
    value("1").map_err(Box::new)
    // note: expected enum `Result<_, Box<(dyn std::error::Error + 'static)>>`
    //          found enum `Result<_, Box<ParseIntError>>`
}

fn ok() -> Result<i32, Box<dyn std::error::Error>> {
    match value("1") {
        Ok(t) => Ok(t),
        Err(e) => Err(Box::new(e)),
    }
}

fn main() {}

Check out this other thread from today/yesterday, it's pretty much the same question.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.