是否有打开或循环继续的快捷方式? [英] Is there a shortcut to unwrap or continue in a loop?

查看:98
本文介绍了是否有打开或循环继续的快捷方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一下:

loop {
    let data = match something() {
        Err(err) => {
            warn!("An error: {}; skipped.", err);
            continue;
        },
        Ok(x) => x
    };

    let data2 = match somethingElse() {
        Err(err) => {
            warn!("An error: {}; skipped.", err);
            continue;
        },
        Ok(x) => x
    };

    // and so on
}

如果我不需要将ok值分配给data,我会使用if let Err(err) = something(),但是上面代码的快捷方式是避免复制粘贴Err/Ok分支我认为,这是典型的情况吗?像if let这样的东西也可以返回ok值.

If I didn't need to assign the ok-value to data, I'd use if let Err(err) = something(), but is there a shortcut to the code above that'd avoid copy-pasting the Err/Ok branches on this, I think, typical scenario? Something like the if let that would also return the ok-value.

推荐答案

虽然我认为E_net4的答案可能是最好的答案,但我为后代添加了一个宏,以防创建单独的函数并使用?运算符由于某种原因是不可取的.

While I think that E_net4's answer is probably the best one, I'm adding a macro for posterity in case creating a separate function and early-returning with the ? operator is for some reason undesirable.

这是一个简单的skip_fail!宏,当传递错误时,该宏continue是一个包含循环:

Here is a simple skip_fail! macro that continues a containing loop when passed an error:

macro_rules! skip_fail {
    ($res:expr) => {
        match $res {
            Ok(val) => val,
            Err(e) => {
                warn!("An error: {}; skipped.", e);
                continue;
            }
        }
    };
}

此宏可用作let ok_value = skip_fail!(do_something());

游乐场链接,该链接使用skip_fail打印出可被1、2整除的数字.和3,并在其中一个分区截断时显示错误.

我再次相信,在单独的函数中使用?,如果没有失败则返回Ok(end_result),这可能是最惯用的解决方案,因此,如果您可以使用该答案,您应该应该这样做.

Again, I believe that using ? in a separate function, and returning an Ok(end_result) if nothing fails, is probably the most idiomatic solution, so if you can use that answer you probably should.

这篇关于是否有打开或循环继续的快捷方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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