You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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>)