有没有办法在没有宏的情况下简化将 Option 转换为 Result 的过程? [英] Is there a way to simplify converting an Option into a Result without a macro?

查看:36
本文介绍了有没有办法在没有宏的情况下简化将 Option 转换为 Result 的过程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的东西(真正的功能是 Ini::Section::get 来自 rust-ini):

I have something like this (the real function is Ini::Section::get from rust-ini):

impl Foo {
    pub fn get<K>(&'a mut self, key: &K) -> Option<&'a str>
    where
        K: Hash + Eq,
    {
        // ...
    }
}

我必须多次调用它:

fn new() -> Result<Boo, String> {
    let item1 = match section.get("item1") {
        None => return Result::Err("no item1".to_string()),
        Some(v) => v,
    };
    let item2 = match section.get("item2") {
        None => return Result::Err("no item2".to_string()),
        Some(v) => v,
    };
}

为了消除代码膨胀,我可以写一个这样的宏:

To remove code bloat, I can write a macro like this:

macro_rules! try_ini_get {
    ($e:expr) => {
        match $e {
            Some(s) => s,
            None => return Result::Err("no ini item".to_string()),
        }
    }
}

有没有办法在没有这个宏实现的情况下去除代码重复?

Is there any way to remove the code duplication without this macro implementation?

推荐答案

ok_orok_or_else 方法将 Options 转换为 Results,以及 ? 运算符自动化与早期 Err 返回相关的样板.

The ok_or and ok_or_else methods convert Options to Results, and the ? operator automates the boilerplate associated with early Err returns.

你可以这样做:

fn new() -> Result<Boo, String> {
    let item1 = section.get("item1").ok_or("no item1")?;
    let item2 = section.get("item2").ok_or("no item2")?;
    // whatever processing...
    Ok(final_result)
}

这篇关于有没有办法在没有宏的情况下简化将 Option 转换为 Result 的过程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆