Closed
Description
Feature gate: #![feature(result_swap)]
This is a tracking issue for result_swap
I propose the addition of a swap
method for the Result
type that would basically turn an Ok
into an Err
and the other way around.
Motivation
This would obviously allow more straightforward code when one need to propagate the success type of a function as an error.
fn my_function(vec: &mut Vec<u8>) -> Result<usize, usize> {
// The value should not be found in the given vector.
let b = vec.binary_search(&10).swap()?;
vec.insert(b, 10);
Ok(b)
}
Used with the Result
constructors that are present on Option
, this method also can come in handy.
fn expect_none(o: Option<u8>) -> Result<(), u8> {
o.ok_or(()).swap()
}
Note that this second case could also be fixed with something like err_or
(being discussed here #80190).
Steps
- Initial implementation (PR Implementation of
Result::swap
and tests #81323) -
- Write tests
- Adjust documentation
- Stabilization PR
Unresolved Questions
- The name
swap
may be confused with the already-used semantic ofmem::swap
orslice::swap
which both have a slightly different meaning. The alternative I had for this matter was the namenot
(the function basically inverts the meaning of theResult
) but I think it makes it even more confusing. - Do we want an
Option::swap
equivalent that would mapSome(old_value)
toNone
andNone
toSome(new_value)
wherenew_value
is a parameter ofOption::swap
? Such a function would probably require aOption::swap_with
counterpart that takes aFnOnce() -> T
.