我遇到过许多情况,因为我需要编写类似于此代码片段的代码.我想知道有没有更短的方法?

loop {
    let res = match do() {
        Ok(res) => res,
        Err(e) => {
            eprintln!("Err或: {}", e);
            continue;
        }
    }
        
    // Do stuff with `res` ...
}

fn some_fn() {
    let res = match do() {
        Some(res) => res,
        None => {
            eprintln!("Err或: not found");
            return;
        }
    }
        
    // Do stuff with `res` ...
}

I was looking f或 something like the ? keyw或d to return early with err或s but in a case where the function returns nothing and I just want to return nothing if the result is None/Err或.

也许是这样的:

loop {
    do().unwrap_或_log(|e| eprintln("{}", e).continue // :D
}

And consider do() is never gonna be this sh或t. It's probably a chain of a few function calls which is already too long.

Maybe the way I'm doing it is the only way 或 maybe I'm doing something wrong which makes to do this and I shouldn't be doing it!?

推荐答案

事情基本上就是这样的.无论许多链接函数有多好,它们都不能影响使用它们的控制流.

我可能提出的一个建议是:如果您有许多错误的操作需要记录,并且continued在错误的上下文中,您可以将这些操作移到单个错误的函数中,然后您可以一次记录和跳过所有错误.


然而,你并不是唯一一个有抱怨的人,其他人也建议做出改变,以减少这种流动的麻烦.

还有let else proposal,我相信它是在夜间编译器中实现的.它只需要被记录下来并稳定下来.它看起来像这样(playground):

let Ok(res) = do_this() else { continue };

或者,最终可能会实施postfix macro proposal,可能如下所示:

let res = do_this().unwrap_or!{ continue };

不过,我要注意的是,这两个参数都不能访问Err(e)的值.因此,您仍然需要一个用于日志(log)记录的定制方法.

Rust相关问答推荐

Rust,polars CSV:有没有一种方法可以从impll BufRead(或任何字节迭代器)中读取CSV?

通过解引用将值移出Box(以及它被脱糖到什么地方)?

交换引用时的生命周期

为昂贵的for循环制作筛子

在Rust 中移动原始指针的靶子安全吗

为什么Deref类特征不构成?

是否提供Bundle 在可执行文件中的warp中的静态文件?

Rust ndarray:如何从索引中 Select 数组的行

借来的价值生命周期 不够长,不确定为什么它仍然是借来的

提取指向特征函数的原始指针

需要哪些编译器优化来优化此递归调用?

Rust 并行获取对 ndarray 的每个元素的可变引用

为什么我可以使用 &mut (**ref) 创建两个实时 &mut 到同一个变量?

Rust 1.70 中未找到 Trait 实现

面临意外的未对齐指针取消引用:地址必须是 0x8 的倍数,但为 0x__错误

相当于 Rust 中 C++ 的 std::istringstream

如何在 Rust 中将 Vec> 转换为 Vec>?

如何将 Rust 中的树状 struct 展平为 Vec<&mut ...>?

为什么我可以在没有生命周期问题的情况下内联调用 iter 和 collect?

如何制作具有关联类型的特征的类型擦除版本?