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)
}
}
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() })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With