gpt4 book ai didi

In what situation `..._or()` is better than `..._or_else(|| {})` and why?(在什么情况下`..._or()`比`..._or_Else(||{})`好?为什么?)

转载 作者:bug小助手 更新时间:2023-10-25 18:10:18 27 4
gpt4 key购买 nike



If the variant ..._or_else() is executed only when it's needed

如果变量..._or_Else()仅在需要时执行


// example
let value = option.unwrap_or_else(|| compute_value(argument));
// only executed if `option` is of enum variant Option::None

Then is there any situation that ..._or() has any advantage?

那么有没有什么情况是……或者()有什么优势呢?


I understand that, if the result inside ..._or_else() has already been calculated, then using ..._or() can be used without drawback. But is there any advantage in this situation?

我知道,如果已经计算了..._or_Else()中的结果,则可以使用..._or()而不会有任何缺点。但在这种情况下有什么优势吗?


I have tried situation and found the clippy rule that suggest to change from ..._or_else() to ..._or() and I am having difficulty understanding the reason of this rule:

我试过了情景,发现了建议从...或_Else()更改为..._or()的快速规则,但我很难理解该规则的原因:



Why is this bad?


Using eager evaluation is shorter and simpler in some cases.


Known problems


It is possible, but not recommended for Deref and Index to have side effects. Eagerly evaluating > them can change the semantics of the program.



更多回答
优秀答案推荐

Using *_or instead of *_or_else when you already have the value saves at least 7 characters (_else and || possibly more {}), so it's less noise.

当您已经有值时,使用*_or而不是*_or_Else可节省至少7个字符(_Else和||可能更多{}),因此噪音较小。


It also results in creating one fewer closure—which might be unknown or unfamiliar syntax to a new Rustacean or developer of another programming language—whether that makes a measurable difference in performance or compile time I'm not sure but it is definitely less work for the compiler and for the people reading the code.

它还导致创建更少的闭包-对于新Rustacean或另一种编程语言的开发人员来说,这可能是未知或不熟悉的语法-这是否会在性能或编译时间方面产生可测量的差异我不确定,但对于编译器和阅读代码的人来说,这肯定是更少的工作。


更多回答

With optimization they compile to the exact same code, at least in a basic situation (godbolt). In debug mode however, the *_or version is much shorter and almost certainly faster.

通过优化,它们编译成完全相同的代码,至少在基本情况下是这样(Godbolt)。然而,在调试模式下,*_or版本要短得多,而且几乎可以肯定更快。

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com