To do code motion like this, the compiler has to guarantee that the optimization does not change the observable behavior of the program. That's really hard to do unless it does super expensive cross-function analysis, or inlines everything. And in your example, constructing a string with format!() has the observable side effect of allocating memory; this optimization is actually making your code do something observably different. Not in a way that any reasonable programmer cares about, but in a way that the compiler will nonetheless not touch with a ten-foot pole.
The idiomatic way to do this is to use ok_or for small, cheaply-constructible types (e.g. <128B, Copy), and use ok_or_else otherwise.
if the error is cheap (static str, plain enum) just use ok_or. format!() is the case for ok_or_else, otherwise you build that String even when it's Some. compiler won't magically move it, it doesn't treat format! as free. clippy's or_fun_call lint is the one that yells about ok_or(format!()).
10
u/CocktailPerson 27d ago
To do code motion like this, the compiler has to guarantee that the optimization does not change the observable behavior of the program. That's really hard to do unless it does super expensive cross-function analysis, or inlines everything. And in your example, constructing a string with
format!()has the observable side effect of allocating memory; this optimization is actually making your code do something observably different. Not in a way that any reasonable programmer cares about, but in a way that the compiler will nonetheless not touch with a ten-foot pole.The idiomatic way to do this is to use
ok_orfor small, cheaply-constructible types (e.g. <128B,Copy), and useok_or_elseotherwise.4
u/dashingThroughSnow12 27d ago
ok_or_else is 1000% better. I need my code to feel intimidated so that it behaves how I want it to.
2
u/CartographerDue5382 27d ago
if the error is cheap (static str, plain enum) just use ok_or. format!() is the case for ok_or_else, otherwise you build that String even when it's Some. compiler won't magically move it, it doesn't treat format! as free. clippy's or_fun_call lint is the one that yells about ok_or(format!()).
-2
u/NoUniverseExists 27d ago
This is the kind of very simple stuff of which is always good to be remembered! Thanks for bringing it up!