When doing error catching I usually make a function return a result. But I feel like writing Result<type, Box<...>> everytime is really verbose, is there some built-in shorthand for this?
fn something() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}
You can just define a type alias with generic arguments. Many crates do like this:
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
fn something() -> Result<()> {
Ok(())
}
The anyhow
crate, written by the author of serde, is designed around an ergonomic alternative to Box<dyn std::error::Error>
called anyhow::Error
. It defines anyhow::Result<T>
as alias for Result<T, anyhow::Error>
:
fn something() -> anyhow::Result<()> {
Ok(())
}
The downside is that it's an external crate, although a very popular and well-tested one.
The upside is that you get good ergonomics, additional features (such as context()
and with_context()
on Result
), as well as non-trivial optimizations - anyhow::Error
is a narrow pointer rather than a wide one, so your Result
s are smaller and more efficient compared to Box<dyn Error>
.
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