Skip to content

Tracking Issue for result_swap #81322

Closed
Closed
@gymore-io

Description

@gymore-io

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

Unresolved Questions

  • The name swap may be confused with the already-used semantic of mem::swap or slice::swap which both have a slightly different meaning. The alternative I had for this matter was the name not (the function basically inverts the meaning of the Result) but I think it makes it even more confusing.
  • Do we want an Option::swap equivalent that would map Some(old_value) to None and None to Some(new_value) where new_value is a parameter of Option::swap? Such a function would probably require a Option::swap_with counterpart that takes a FnOnce() -> T.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-result-optionArea: Result and Option combinatorsC-tracking-issueCategory: 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.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions