-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
Add unwrap_or_put
method to Option<T>
#1405
Comments
or_put
method to Optionunwrap_or_put
method to Option
unwrap_or_put
method to Optionunwrap_or_put
method to Option<T>
The code you've written would not compile beceause you need to take You would need to return a reference if you want to take a reference. If you want this behavior to mutate If however, you just want a function that takes (&Option, T) -> &T, this brief composition will achieve that effect:
This will not change the state of the original option, though. |
I see, perhaps the following would be a more feasible version of what I want: fn or_put(&mut self, foo : T) -> &mut Option<T> {
if self.is_none() { *self = Some(foo); }
self
} |
@leodasvacas Why not just use |
Because I wish to mutate the original option without consuming it, which I believe that code achieves? |
Actually, I'm wrong. I must have misunderstood what you want. You want a way to place a value if it's none. |
@leodasvacas I strongly suggest you to create a crate implementing functionality you seek and perhaps then petition for inclusion to the standard library. To me it seems you only have a vague idea of what you want to achieve and implementing a crate will both make implementation available to you sooner and make clear how you want your idea to be implemented from an API standpoint. |
Can we reopen this one (and probably close #1416)? This seems like an important missing feature for field initialization. As in the original example in the thread, it's particularly important when |
@stuhood small changes don't need to go through an RFC today; I would just send in a PR for this. |
Looks like this landed for rust-lang/rust#39288 as shahn/rust@8e02ad0 ... thanks @shahn! |
Originally suggested in #1278, an
unwrap_or_put
method onOption<T>
would be useful, a common use case is lazy initialization. To illustrate the behaviour:The text was updated successfully, but these errors were encountered: