by svieira · 3y ago · 0 comments
pub fn find_user(username: &str) -> Result<UserId, MyError> {
let f = std::fs::File::open("/etc/passwd")
.map_err(|e| format!("Failed to open password file: {:?}", e))?;
// ...
}
and an error type: #[derive(Debug)]
pub struct MyError(String);
impl std::fmt::Display for MyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::error::Error for MyError {}
And an implementation of `From<String>` for `MyError`: impl std::convert::From<String> for MyError {
fn from(msg: String) -> Self {
Self(msg)
}
}
The book asserts:> When it encounters the question mark operator (?), the compiler will automatically apply any relevant From trait implementations that are needed to reach the destination error return type.
I thought that `?` only unwrapped `Option` and `Result` and was not overloadable. Is [the Rust doc on `?`][1] leaving something important out, or is this a mis-statement?
[1]: https://doc.rust-lang.org/reference/expressions/operator-exp...
`?` works off off the Try trait (https://doc.rust-lang.org/std/ops/trait.Try.html), which is unstable so you can’t currently implement it in userland (except on nightly), and it is implemented on more than Option and Result, specifically ControlFlow (https://doc.rust-lang.org/std/ops/enum.ControlFlow.html).
So whether it’s important to mention depends mostly on how important you think try_fold and try_for_each are, and if you think you’ll miss the information if ever you need those given that’s clearly mentioned in the ControlFlow docs.
This is still true, although the experimental Try trait in nightly does provide this. `From` is applied to the Error of the returned Result, ie. Result<T, String> => Result<T, MyError>.
Not since the addition of ControlFlow.