最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

rust - Miette Result type from Option? - Stack Overflow

programmeradmin5浏览0评论

I'm trying to be a grown up about how I handle errors in my rust code, and not just unwrap everything. I'm currently using Miette.

I want to be able to use the ?; syntax, preferably in a very lightweight way. I'm running into problems with what seems like it should be a very easy and common case - converting an Option into a Result.

pub fn foo() -> miette::Result<String>{
    let result = bar().some_function("Bar gave us nothing")?;
    Ok(result)
}
fn bar () -> Option<String>{
    Some("bar".to_string())
}

I've tried a bunch of options to make some_function work, but they all end up messy. The best I've managed to do so far is:

pub fn foo() -> miette::Result<String>{
    let result =  match bar(){
        Some(s) => Ok::<String, miette::Report>(s),
        None => miette::bail!("No bar")
    }?;

    Ok(result)
}
fn bar () -> Option<String>{
    Some("bar".to_string())
}

That seems to work but it'd be a pain to use everywhere... I could wrap it into a custom function and even make some trait in my project implemented on Option<T>, but I feel like I'm missing something obvious. What's the idiomatic way to approach this?

EDIT:

After some fiddling, I found that

let result =  bar().ok_or(miette::Error::msg("Bar Failed"))?;

works. That's vaguely acceptable but I'd still like to clean it up more, ideally down to a single call... is there a better way?

发布评论

评论列表(0)

  1. 暂无评论