I'm using Anyhow and have a function that returns anyhow::Result
. In that function I want to "unwrap" an option so that if the option value is None
, an error with a specific error message to be returned. That's what I've done:
let o: Option<i32> = ...;
let v: i32 = o.ok_or_else(|| anyhow!("Oh, boy!"))?;
// here I need v only
I've used ok_or_else()
instead of ok_or()
for performance reasons.
I'm generally fine with that but was wondering if that's the simplest (most concise) way to do what I want (w/o sacrificing performance)?
You should use context
(playground):
use anyhow::{Context, Result};
fn _foo(o: Option<i32>) -> Result<i32> {
let v = o.context("Oh, boy!")?;
Ok(v)
}
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