Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return `map_err` for result fails

Tags:

rust

I am figuring out why the following fails when returning map_err:

Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
  --> src/main.rs:37:5
   |
36 | fn R() -> Result<i32, MyError> {
   |           -------------------- expected `std::result::Result<i32, MyError>` because of return type
37 |     decode().map_err(|e| Err(MyError {v: "changed".to_string() }))
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `MyError`, found enum `std::result::Result`
   |
   = note: expected enum `std::result::Result<_, MyError>`
              found enum `std::result::Result<_, std::result::Result<_, MyError>>`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground`.

If I use match and map it manually it works.

Code:

use std::error::Error;
use std::fmt;
use std::fmt::Display;

#[derive(Debug)]
struct MyError {
    v: String,
}

impl MyError {
    fn new() -> MyError {
        MyError {
            v: "oh no!".to_string()
        }
    }

    fn change_message(&mut self, new_message: &str) {
        self.v = new_message.to_string();
    }
}

impl Error for MyError {}

impl Display for MyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "MyError: {}", &self.v)
    }
}

fn decode() -> Result<i32, MyError> {
    Err(
        MyError::new()
    )
}

fn R() -> Result<i32, MyError> {
    decode().map_err(|e| Err(MyError {v: "changed".to_string() }))
}

fn main() {
    let d = R();
    match d {
        Ok(t) => println!("t {}", t),
        Err(e) => println!("e {}", e)
    }
}
like image 707
Jaynti Kanani Avatar asked Mar 09 '26 06:03

Jaynti Kanani


1 Answers

If you look at the signature for map_err you will see that it expects a closure that takes an error type and returns an error type, not a Result.

decode().map_err(|e| MyError {v: "changed".to_string() })
like image 131
Ross MacArthur Avatar answered Mar 11 '26 09:03

Ross MacArthur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!