为什么我应该更喜欢 `Option::ok_or_else` 而不是 `Option::ok_or`? [英] Why should I prefer `Option::ok_or_else` instead of `Option::ok_or`?
问题描述
我刚刚在拉取请求中看到以下更改:
I just saw the following change in a pull request:
- .ok_or(Error::new(ErrorKind::Other, "Decode error"));
+ .ok_or_else(|| Error::new(ErrorKind::Other, "Decode error"));
我知道的唯一区别是:
- 在
ok_or
中,我们已经通过Error::new
创建了Error
并将其传递给适配器. - 在
ok_or_else
中,我们传递了一个闭包,它会产生这样的值,但如果Option
中有Some
数据,它可能不会被调用>.
- In
ok_or
we have already createdError
byError::new
and passed it into a adaptor. - In
ok_or_else
we have passed a closure which will produce such a value but it may not be called if there isSome
data in theOption
.
我错过了什么吗?
推荐答案
使用 ok_or_else
或 any 的 ..._or_else 的主要原因code> methods 是为了避免在不需要时执行函数.对于
Option::ok_or_else
或Option::unwrap_or_else
,当Option
为Some 时,不需要运行额外的代码代码>.这可以使代码更快,具体取决于错误情况下发生的情况
The primary reason to use ok_or_else
or any of the ..._or_else
methods is to avoid executing a function when it's not needed. In the case of Option::ok_or_else
or Option::unwrap_or_else
, there's no need to run extra code when the Option
is Some
. This can make code faster, depending on what happens in the error case
在这个例子中,Error::new
可能执行分配,但它也可以写入标准输出,发出网络请求,或者任何 Rust 代码可以做的事情;从外面很难分辨.将此类代码放在闭包中通常更安全,这样您就不必担心成功案例发生时的额外副作用.
In this example, Error::new
likely performs allocation, but it could also write to standard out, make a network request, or anything any piece of Rust code can do; it's hard to tell from the outside. It's generally safer to place such code in a closure so you don't have to worry about extraneous side effects when the success case happens.
Clippy 也为您整理了这个:
Clippy lints this for you as well:
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
这篇关于为什么我应该更喜欢 `Option::ok_or_else` 而不是 `Option::ok_or`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!