使用..._or_else
个方法中的ok_or_else
个或any个的主要原因是避免在不需要的时候执行函数.在Option::ok_or_else
或Option::unwrap_or_else
的情况下,当Option
为Some
时,不需要运行额外的代码.这可以使代码更快,这取决于错误情况下发生的情况
在本例中,Error::new
可能执行分配,但它也可以写入标准输出、发出网络请求,或者任何一段 rust 迹代码都可以执行的操作;从外面很难分辨.通常,将这样的代码放在闭包中更安全,这样在成功 case 发生时就不必担心额外的副作用.
Clippy lints也为你准备了这个:
fn main() {
let foo = None;
foo.unwrap_or("hello".to_string());
}
warning: use of `unwrap_or` followed by a function call
--> src/main.rs:3:9
|
3 | foo.unwrap_or("hello".to_string());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: try this: `unwrap_or_else(|| "hello".to_string())`
|
= note: `#[warn(clippy::or_fun_call)]` on by default
= help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#or_fun_call