Simplest way to unwrap an option and return Error if None (Anyhow)

Viewed 2124

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)?

1 Answers

You should use context (playground):

use anyhow::{Context, Result};

fn _foo(o: Option<i32>) -> Result<i32> {
    let v = o.context("Oh, boy!")?;
    Ok(v)
}
Related