简体   繁体   中英

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

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> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM