Here is a minor stylistic question: which of the following would you prefer, calling unwrap_or_else
:
fn foo() -> Result<Bar, E> {
let x: Option<Bar> = bar();
let y = x.unwrap_or_else(|| return Err(ErrOther::new(..).into()) );
/* use y */
}
or ok_or_else
and unwrapping using the ?
operator:
fn foo() -> Result<Bar, E> {
let x: Option<Bar> = bar();
let y = x.ok_or_else(|| ErrOther::new(..))?;
/* use y */
}
Written as such, the first option is more boilerplaty and could also require a conversion between error types. Syntactically, I'm really interested in the more pretty version using anyhow
macros:
fn foo() -> anyhow::Result<Bar> {
let x: Option<Bar> = bar();
let y = x.unwrap_or_else(|| bail!(..));
/* use y */
}
// VS
fn foo() -> anyhow::Result<Bar> {
let x: Option<Bar> = bar();
let y = x.ok_or_else(|| anyhow!(..))?;
/* use y */
}
Not that it matters much, but I wonder whether you would prefer one version over the other if you had to read really many unwraps.