Closed
Description
sometimes, particularly when interfacing with C libraries which provide their own errno-like API (GetLastError
, SDL_GetError
, etc), Rust bindings may opt to return Option<ErrorType>
to model the absence of an error.
This could then be 'upgraded' to a Result<T, E>
, in a manner similar to ok_or
:
fn example() -> Result<(), SomeError> {
get_some_error().err_or(())
}
pros
- fixes a papercut with error modeling and error handling
- api requires minimal consideration since it already has a stable counterpart (as well as unstable siblings:
unwrap_none
/expect_none
Tracking issue for Option::expect_none(msg) and unwrap_none() #62633)
cons
- name looks like
error
, might cause confusion - not extremely common use case? (haven't checked discussion on
unwrap_none
yet)
Metadata
Metadata
Assignees
Labels
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
result_swap
#81322joshtriplett commentedon Aug 2, 2021
What's the advantage of returning
Option<ErrorType>
rather thanResult<(), ErrorType>
? Semantically, the latter feels more accurate. And both are capable of handling niches in the same way.m-ou-se commentedon Aug 11, 2021
We discussed this briefly in the library api team meeting last week, and we'd like to see some concrete use cases. Do you have examples from some Rust crates where this
Option
toResult::Err
conversion would be used?yaahc commentedon Sep 27, 2021
Closing this for now due to lack of responses with concrete use cases. Feel free to reopen in the future if you have a use case where you feel this API would be justified.
NathanielB123 commentedon Jan 2, 2023
I think I have a concrete use-case for this. I am using the
insert
function inHashMap<K, V>
which returnsOption<V>
if there is already an item in the hash map. In my code, and I would argue probably most of the time, an item already being present in the hash map implies some error has occurred, and so I want to returnResult<SuccessType, V>
.err_or_else
would be perfect for this.