If the variant ..._or_else()
is executed only when it's needed
// 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?
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:
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.
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.