diff options
| author | bors <bors@rust-lang.org> | 2017-09-12 09:54:59 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2017-09-12 09:54:59 +0000 |
| commit | 817e1b81e230d599585f860cdcad96c5ed83b93e (patch) | |
| tree | c8b45bc0eaa2d61bf3b1dbbd941b41dbefcc9f31 /src/libstd | |
| parent | 8fc0fc8c2d9718f8b664afca8e28636a6099e2b8 (diff) | |
| parent | 9389d26ba261119bec1dc5336d17ce23c34785b7 (diff) | |
Auto merge of #44344 - jonhoo:entry_or_default, r=BurntSushi
Add or_default to Entry APIs As argued for in #44324, this PR adds a new `or_default` method to the various `Entry` APIs (currently just for `BTreeMap` and `HashMap`) when `V: Default`. This method is effectively a shorthand for `or_insert_with(Default::default)`.
Diffstat (limited to 'src/libstd')
| -rw-r--r-- | src/libstd/collections/hash/map.rs | 27 |
1 files changed, 27 insertions, 0 deletions
diff --git a/src/libstd/collections/hash/map.rs b/src/libstd/collections/hash/map.rs index 16b0c709986..fbb69ca9749 100644 --- a/src/libstd/collections/hash/map.rs +++ b/src/libstd/collections/hash/map.rs @@ -2001,6 +2001,33 @@ impl<'a, K, V> Entry<'a, K, V> { } } +impl<'a, K, V: Default> Entry<'a, K, V> { + #[unstable(feature = "entry_or_default", issue = "44324")] + /// Ensures a value is in the entry by inserting the default value if empty, + /// and returns a mutable reference to the value in the entry. + /// + /// # Examples + /// + /// ``` + /// #![feature(entry_or_default)] + /// # fn main() { + /// use std::collections::HashMap; + /// + /// let mut map: HashMap<&str, Option<u32>> = HashMap::new(); + /// map.entry("poneyland").or_default(); + /// + /// assert_eq!(map["poneyland"], None); + /// # } + /// ``` + pub fn or_default(self) -> &'a mut V { + match self { + Occupied(entry) => entry.into_mut(), + Vacant(entry) => entry.insert(Default::default()), + } + } + +} + impl<'a, K, V> OccupiedEntry<'a, K, V> { /// Gets a reference to the key in the entry. /// |
