3 ms·
> But yeah I constantly get confused by when errors can and can not coerce. It's simple, really. `?` coerces errors if there's an `impl From<InnerError> for Ou
by Expurple 1y ago
> But yeah I constantly get confused by when errors can and can not coerce.
It's simple, really. `?` coerces errors if there's an `impl From<InnerError> for OuterError`:
fn outer() -> Result<(), OuterError> {
inner()?;
Ok(())
}
When OuterError is your own type, you can always add that impl. When it's a library type, you're at its mercy. E.g., the point of anyhow::Error is that it's designed to automatically wrap any other error. To do that, anyhow provides an
impl<E> From<E> for anyhow::Error
where
E: Error + Send + Sync + 'static
- forrestthewoods 1y agoI regularly get super confused by what coerces and what doesn’t. I swear there’s cases where ? works but into() does not. It’s many things. But simple ain’t one of them =D
- Expurple 1y agoI'm not aware of such cases. And The Rust Reference says [1]: > If the value is Err(e), then it will return Err(From::from(e)) from the enclosing function or closure. Without a specific example, I can't help you further. [1]: https://doc.rust-lang.org/stable/reference/expressions/operator-expr.html#r-expr.try.effects-err https://doc.rust-lang.org/stable/reference/expressions/opera...