Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust shorthand for Result<type, Box<dyn std::error::Error>>

Tags:

rust

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(())
}
like image 220
grawat Avatar asked Dec 30 '22 12:12

grawat


2 Answers

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(())
}
like image 118
Alexey Larionov Avatar answered Feb 12 '23 01:02

Alexey Larionov


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 Results are smaller and more efficient compared to Box<dyn Error>.

like image 30
user4815162342 Avatar answered Feb 12 '23 01:02

user4815162342