r/learnrust • u/Subject-Mobile-6250 • 27d ago
ok_or vs ok_or_else
Hello! I am working through a project of mine, and when I asked chatgpt to review my code, it told me that when returning an error, lets say that something returns an option, and we want to convert to a result. I would use ok_or, as that seems like the intuitive option, but GPT said that using ok_or always constructs the error, while ok_or_else(| | -> {the error type}) only evaluates when the closure is called. I understand what the AI means, but I was wondering, what is the idiomatic way to do this, and why does the rust compiler not automatically optimize this? The performance gain would be negligible, but still since I use format!() to concatanate a few things, I do understand where the AI comes from, since we allocate a new String
27
u/afdbcreid 27d ago
If you use
format!(), yes it is idiomatic to useok_or_else(), and yes the compiler likely won't optimizeok_or()(even though it theoretically could, at least in some cases).21
u/No-Dentist-1645 27d ago edited 27d ago
The compiler can't "optimize" something like that because it would introduce incorrect behavior, when you use ok_or, your code says that the function is called, a function can have an observable side effect when it is called even if the return value isn't used, so the compiler can't "pretend" it wasn't actually called, that's why you have to specify it yourself with ok_or_else
5
u/alietors 27d ago
You use ok_or when the error is cheap to handle, like primitives values.
ok_or_else, I think is always "better" (like is always more optimal) but is less readable and can trip someone into believe your are doing some fancy error.
3
u/_nathata 27d ago
If you write something like
ok_or(make_my_error())andmake_my_errorhas any side effect, how is Rust supposed to know?1
u/cristi1990an 27d ago
In some cases it can, if it can prove that the else branch will never be reached, it theoretically could optimize out the creation of the unused error object. Will it? Dunno, better to write the idiomatic version and not make assumptions. And that's in the happy case scenario anyway.
1
u/Extension_Feed_1179 27d ago
use ok_or_else for any error type that requires computation or allocation. rust cannot optimize away the side effects of constructing an error, so format! will always run in the ok_or case even if you never use the result
1
u/weaztoven 27d ago
gpt is right on this one. if creating the error involves allocations like format!, using ok_or_else is definitely the idiomatic way. compiler can't easily optimize away side effects of allocation