Currently, Option<T> has the method take, which is implemented as replace(&mut self, None). To complement this method, I propose adding a give as well:
pub fn give(&mut self, val: T) -> Option<T> {
::std::mem::replace(self, Some(val))
}
#[test]
fn it_works() {
let mut opt = None;
assert_eq!(opt.give(5), None);
assert_eq!(opt, Some(5));
assert_eq!(opt.give(6), Some(5));
assert_eq!(opt, Some(6));
}
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.
Currently,
Option<T>has the methodtake, which is implemented asreplace(&mut self, None). To complement this method, I propose adding agiveas 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.