Skip to content

There's no clean way to move a value into an Option and get a reference to the value. #29203

Closed
@canndrew

Description

@canndrew

I need to mutate an Option in place, setting it to Some(x), then get a reference to x. The only way to do this is:

*my_opt = Some(x);
let r = match *my_opt {
    Some(ref x) => x,
    None => unreachable!(),
}

I shouldn't need to pattern-match against my_opt if I already know that it's a Some. Having to use unreachable!() creates code-smell - it's often a red flag that code is wrong and if it isn't wrong it should ideally be possible to restructure it to get rid of the unreachable!().

This is actually a problem with enums generally but without a way to fix the more general problem I think it should at least be fixed for Option.

I propose that either one of the following methods should be added to Option<T>

// Insert a value into the `Option`, setting it to `Some(val)` and returning a reference to `val`
fn insert(&mut self, val: T) -> &mut T

// Insert a value into the `Option`, setting it to `Some(val)` and returning a reference to `val`
// along with the previous value in the `Option` (if there was one)
fn insert(&mut self, val: T) -> (&mut T, Option<T>)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions