当选项为None时,从函数返回结果或选项以外的值的惯用方式?

时间:2019-01-10 00:40:49

标签: error-handling rust idiomatic

我想这样做:

fn foo(bar: Option<...>) -> ... {
    if let None = bar { // bar is None. No need to go any further
        return ...
    }

    /* Do some complex calculation assuming bar is Some(...) */
}

这种方法适用于非类型化语言,甚至对一些类型化语言(如TypeScript和Swift,如果我对内存没问题的话)来说都是Swift的,但对Rust却不行。

对于除OptionResult以外的返回类型起作用的惯用方式是什么?我可以做到:

if let Some(...) = bar {
    /* complex calculation */
} else {
    return ...
}

从长远来看,这似乎类似于许多不可读的嵌套if-else子句,带有很多缩进。

0 个答案:

没有答案