我想这样做:
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却不行。
对于除Option
和Result
以外的返回类型起作用的惯用方式是什么?我可以做到:
if let Some(...) = bar {
/* complex calculation */
} else {
return ...
}
从长远来看,这似乎类似于许多不可读的嵌套if-else子句,带有很多缩进。