6 ms·
https://www.lurklurk.org/effective-rust/errors.html#minimal-errors https://www.lurklurk.org/effective-rust/errors.html#minimal-... has what seems (to my naive u
by svieira 3y ago
https://www.lurklurk.org/effective-rust/errors.html#minimal-errors https://www.lurklurk.org/effective-rust/errors.html#minimal-... has what seems (to my naive understanding) to be mis-statement. Given a trait:
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-expr.html#the-question-mark-operator https://doc.rust-lang.org/reference/expressions/operator-exp...
- deleted 3y ago[deleted]
- ben-schaaf 3y ago> I thought that `?` only unwrapped `Option` and `Result` and was not overloadable. 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>.
- masklinn 3y ago> This is still true Not since the addition of ControlFlow.
- masklinn 3y agoThe Rust doc is leaving things out, though whether it’s important is a complicated question. `?` works off off the Try trait (https://doc.rust-lang.org/std/ops/trait.Try.html 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 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.
- ezrast 3y agoThe "relevant From trait implementations" are the ones defined on the value wrapped by the Option or Result.