Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 317
at54321 Avatar asked Sep 02 '25 02:09

at54321


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)
}
like image 104
eggyal Avatar answered Sep 05 '25 01:09

eggyal