-
Notifications
You must be signed in to change notification settings - Fork 13.9k
Closed
Labels
A-result-optionArea: Result and Option combinatorsArea: Result and Option combinatorsC-tracking-issueCategory: An issue tracking the progress of sth. like the implementation of an RFCCategory: An issue tracking the progress of sth. like the implementation of an RFCT-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.Relevant to the library API team, which will review and decide on the PR/issue.
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::swapand tests #81323) -
- Write tests
- Adjust documentation
- Stabilization PR
Unresolved Questions
- The name
swapmay be confused with the already-used semantic ofmem::swaporslice::swapwhich 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::swapequivalent that would mapSome(old_value)toNoneandNonetoSome(new_value)wherenew_valueis a parameter ofOption::swap? Such a function would probably require aOption::swap_withcounterpart that takes aFnOnce() -> T.
Metadata
Metadata
Assignees
Labels
A-result-optionArea: Result and Option combinatorsArea: Result and Option combinatorsC-tracking-issueCategory: An issue tracking the progress of sth. like the implementation of an RFCCategory: An issue tracking the progress of sth. like the implementation of an RFCT-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.Relevant to the library API team, which will review and decide on the PR/issue.