-
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 give
method to Option<T>
#1416
Comments
I haven't had a need for this, but I do like the symmetry 👍 |
nit: personally, I'd call it offer. |
|
This seems to provide the same functionality as the methods requested in #1405 and #1278. While this proposal is symmetrical with take, I find the return value here really confusing (like difficult to reason about even with the code in front of me, which is not true of take) and don't know when it would be useful. |
I find this very confusing. let x = val.take();
*val = Some(y); if val.is_none() {
*val = Some(x);
} else {
// process val
} |
I think |
So fn put(&mut self, val: T) -> &T {
match *self {
Some(ref item) => item,
None => {
self = Some(val);
self.as_ref().unwrap()
}
}
} |
@withoutboats More like fn put(&mut self, val: T) -> Option<T> {
mem::replace(self, Some(val))
} For your suggestion, a more descriptive name like |
That would replace the value even if the value is |
There is no reason to have a Yes, I suppose a |
Just to clarify, |
The behavior @cybergeek94 suggested is the same as |
I recently proposed something similar however I came to the conclusion that this would be a bad API because after being called it guarantees that the option will be |
Huh, I read this on the docs for insert a few weeks ago, and it must have changed. In that case, I totally agree that a |
A |
unwraping option with result is nice but setting the value may be confusing when u dont know what is underneath the api. also writing Some(3) is not that inefficient |
Tracked in rust-lang/rust#51998. |
Currently,
Option<T>
has the methodtake
, which is implemented asreplace(&mut self, None)
. To complement this method, I propose adding agive
as well:This follows the same standard that
HashMap
,BTreeMap
, and other collections use. Inserts a value into the option and returns the old value.I feel like this is a common enough pattern to warrant a method from the standard library.
The text was updated successfully, but these errors were encountered: