-
Notifications
You must be signed in to change notification settings - Fork 13.3k
There's no clean way to move a value into an Option and get a reference to the value. #29203
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
The example code is just a way more verbose version of: *my_opt = Some(x);
let r = my_opt.as_ref().unwrap(); Still not as clean as let r = my_opt.insert(x); But certainly much less dire. I've felt this pain, but I'm not totally sold if it's worth it. Note also that the code you demonstrate cannot be expressed by insert. Insert takes |
D'oh, I didn't think of that. I feel the same way about
I'm not sure what your point is. Mutably borrowing the Option is the intention. |
This is not what your example code does, so this wasn't clear. |
The more general fix to this problem, fwiw, would probably be a combination of the extended enums proposal (so that variants have types) along with a refinement type system that allows us to give more precise, flow-dependent types to mutable references. It would be cool, but certainly not on the short term horizon. |
Given #29204 (comment), I'm going to give this a close in favor of an RFC. Thanks! |
To help people who come here via google, don't be misled by this issue being closed and seemingly abandoned - |
I need to mutate an
Option
in place, setting it toSome(x)
, then get a reference tox
. The only way to do this is:I shouldn't need to pattern-match against
my_opt
if I already know that it's aSome
. Having to useunreachable!()
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 theunreachable!()
.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>
The text was updated successfully, but these errors were encountered: