With the first method, I have to define a struct UserErr; And with the second method, it will unwrap f and wrap f again.
I wonder,
in the second method, it looks like String format!("User error, and original error: {}", e.to_string()) was auto casted some kind of Error, so which type of Error (a struct that impl trait std::error::Error) this string auto casted ?
How can I use map_err to map error to a customed string without define a new type(struct UserErr in this example)?
If you want to access this via map_err, then you can try calling .into() on your string. This will work if the compiler can infer the target error type.
In this case, the compiler cannot infer the target error type. Is there a good way to implement it without defining a new error?
The code snippet is as following,
let hmap = HashMap::from([("hello", "world")]);
let _ = hmap.get("he").ok_or(format!("error").into())?;
26 | let _ = hmap.get("he").ok_or(format!("error").into())?;
| ^^^^^ ----------------------- this method call resolves to `T`
| |
| cannot infer type for type parameter `E` declared on the associated function `ok_or`
error[E0283]: type annotations needed
The question mark operator inserts a call to into of itself. Since you now have a chain of two into calls, it can't figure out what the intermediate type should be.
Remove the into call and let the question mark do it for you.