extend_one
)extend_one
)Inserts all new key-values from the iterator and replaces values with existing\nkeys with new values returned from the iterator.
\nextend_one
)extend_one
)Creates an empty HashMap
.
The hash map is initially created with a capacity of 0, so it will not allocate until it\nis first inserted into.
\nuse std::collections::HashMap;\nlet mut map: HashMap<&str, i32> = HashMap::new();
Creates an empty HashMap
with at least the specified capacity.
The hash map will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the hash map will not allocate.
use std::collections::HashMap;\nlet mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
hash_raw_entry
)Creates a raw entry builder for the HashMap.
\nRaw entries provide the lowest level of control for searching and\nmanipulating a map. They must be manually initialized with a hash and\nthen manually searched. After this, insertions into a vacant entry\nstill require an owned key to be provided.
\nRaw entries are useful for such exotic situations as:
\nBecause raw entries provide much more low-level control, it’s much easier\nto put the HashMap into an inconsistent state which, while memory-safe,\nwill cause the map to produce seemingly random results. Higher-level and\nmore foolproof APIs like entry
should be preferred when possible.
In particular, the hash used to initialize the raw entry must still be\nconsistent with the hash of the key that is ultimately stored in the entry.\nThis is because implementations of HashMap may need to recompute hashes\nwhen resizing, at which point only the keys are available.
\nRaw entries give mutable access to the keys. This must not be used\nto modify how the key would compare or hash, as the map will not re-evaluate\nwhere the key should go, meaning the keys may become “lost” if their\nlocation does not reflect their state. For instance, if you change a key\nso that the map now contains keys which compare equal, search may start\nacting erratically, with two keys randomly masking each other. Implementations\nare free to assume this doesn’t happen (within the limits of memory-safety).
\nhash_raw_entry
)Creates a raw immutable entry builder for the HashMap.
\nRaw entries provide the lowest level of control for searching and\nmanipulating a map. They must be manually initialized with a hash and\nthen manually searched.
\nThis is useful for
\nUnless you are in such a situation, higher-level and more foolproof APIs like\nget
should be preferred.
Immutable raw entries have very limited use; you might instead want raw_entry_mut
.
Creates an empty HashMap
which will use the given hash builder to hash\nkeys.
The created map has the default initial capacity.
\nWarning: hash_builder
is normally randomly generated, and\nis designed to allow HashMaps to be resistant to attacks that\ncause many collisions and very poor performance. Setting it\nmanually using this function can expose a DoS attack vector.
The hash_builder
passed should implement the BuildHasher
trait for\nthe HashMap to be useful, see its documentation for details.
use std::collections::HashMap;\nuse std::hash::RandomState;\n\nlet s = RandomState::new();\nlet mut map = HashMap::with_hasher(s);\nmap.insert(1, 2);
Creates an empty HashMap
with at least the specified capacity, using\nhasher
to hash the keys.
The hash map will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the hash map will not allocate.
Warning: hasher
is normally randomly generated, and\nis designed to allow HashMaps to be resistant to attacks that\ncause many collisions and very poor performance. Setting it\nmanually using this function can expose a DoS attack vector.
The hasher
passed should implement the BuildHasher
trait for\nthe HashMap to be useful, see its documentation for details.
use std::collections::HashMap;\nuse std::hash::RandomState;\n\nlet s = RandomState::new();\nlet mut map = HashMap::with_capacity_and_hasher(10, s);\nmap.insert(1, 2);
Returns the number of elements the map can hold without reallocating.
\nThis number is a lower bound; the HashMap<K, V>
might be able to hold\nmore, but is guaranteed to be able to hold at least this many.
use std::collections::HashMap;\nlet map: HashMap<i32, i32> = HashMap::with_capacity(100);\nassert!(map.capacity() >= 100);
An iterator visiting all keys in arbitrary order.\nThe iterator element type is &'a K
.
use std::collections::HashMap;\n\nlet map = HashMap::from([\n (\"a\", 1),\n (\"b\", 2),\n (\"c\", 3),\n]);\n\nfor key in map.keys() {\n println!(\"{key}\");\n}
In the current implementation, iterating over keys takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.
\nCreates a consuming iterator visiting all the keys in arbitrary order.\nThe map cannot be used after calling this.\nThe iterator element type is K
.
use std::collections::HashMap;\n\nlet map = HashMap::from([\n (\"a\", 1),\n (\"b\", 2),\n (\"c\", 3),\n]);\n\nlet mut vec: Vec<&str> = map.into_keys().collect();\n// The `IntoKeys` iterator produces keys in arbitrary order, so the\n// keys must be sorted to test them against a sorted array.\nvec.sort_unstable();\nassert_eq!(vec, [\"a\", \"b\", \"c\"]);
In the current implementation, iterating over keys takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.
\nAn iterator visiting all values in arbitrary order.\nThe iterator element type is &'a V
.
use std::collections::HashMap;\n\nlet map = HashMap::from([\n (\"a\", 1),\n (\"b\", 2),\n (\"c\", 3),\n]);\n\nfor val in map.values() {\n println!(\"{val}\");\n}
In the current implementation, iterating over values takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.
\nAn iterator visiting all values mutably in arbitrary order.\nThe iterator element type is &'a mut V
.
use std::collections::HashMap;\n\nlet mut map = HashMap::from([\n (\"a\", 1),\n (\"b\", 2),\n (\"c\", 3),\n]);\n\nfor val in map.values_mut() {\n *val = *val + 10;\n}\n\nfor val in map.values() {\n println!(\"{val}\");\n}
In the current implementation, iterating over values takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.
\nCreates a consuming iterator visiting all the values in arbitrary order.\nThe map cannot be used after calling this.\nThe iterator element type is V
.
use std::collections::HashMap;\n\nlet map = HashMap::from([\n (\"a\", 1),\n (\"b\", 2),\n (\"c\", 3),\n]);\n\nlet mut vec: Vec<i32> = map.into_values().collect();\n// The `IntoValues` iterator produces values in arbitrary order, so\n// the values must be sorted to test them against a sorted array.\nvec.sort_unstable();\nassert_eq!(vec, [1, 2, 3]);
In the current implementation, iterating over values takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.
\nAn iterator visiting all key-value pairs in arbitrary order.\nThe iterator element type is (&'a K, &'a V)
.
use std::collections::HashMap;\n\nlet map = HashMap::from([\n (\"a\", 1),\n (\"b\", 2),\n (\"c\", 3),\n]);\n\nfor (key, val) in map.iter() {\n println!(\"key: {key} val: {val}\");\n}
In the current implementation, iterating over map takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.
\nAn iterator visiting all key-value pairs in arbitrary order,\nwith mutable references to the values.\nThe iterator element type is (&'a K, &'a mut V)
.
use std::collections::HashMap;\n\nlet mut map = HashMap::from([\n (\"a\", 1),\n (\"b\", 2),\n (\"c\", 3),\n]);\n\n// Update all values\nfor (_, val) in map.iter_mut() {\n *val *= 2;\n}\n\nfor (key, val) in &map {\n println!(\"key: {key} val: {val}\");\n}
In the current implementation, iterating over map takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.
\nReturns the number of elements in the map.
\nuse std::collections::HashMap;\n\nlet mut a = HashMap::new();\nassert_eq!(a.len(), 0);\na.insert(1, \"a\");\nassert_eq!(a.len(), 1);
Returns true
if the map contains no elements.
use std::collections::HashMap;\n\nlet mut a = HashMap::new();\nassert!(a.is_empty());\na.insert(1, \"a\");\nassert!(!a.is_empty());
Clears the map, returning all key-value pairs as an iterator. Keeps the\nallocated memory for reuse.
\nIf the returned iterator is dropped before being fully consumed, it\ndrops the remaining key-value pairs. The returned iterator keeps a\nmutable borrow on the map to optimize its implementation.
\nuse std::collections::HashMap;\n\nlet mut a = HashMap::new();\na.insert(1, \"a\");\na.insert(2, \"b\");\n\nfor (k, v) in a.drain().take(1) {\n assert!(k == 1 || k == 2);\n assert!(v == \"a\" || v == \"b\");\n}\n\nassert!(a.is_empty());
hash_extract_if
)Creates an iterator which uses a closure to determine if an element should be removed.
\nIf the closure returns true, the element is removed from the map and yielded.\nIf the closure returns false, or panics, the element remains in the map and will not be\nyielded.
\nNote that extract_if
lets you mutate every value in the filter closure, regardless of\nwhether you choose to keep or remove it.
If the returned ExtractIf
is not exhausted, e.g. because it is dropped without iterating\nor the iteration short-circuits, then the remaining elements will be retained.\nUse retain
with a negated predicate if you do not need the returned iterator.
Splitting a map into even and odd keys, reusing the original map:
\n\n#![feature(hash_extract_if)]\nuse std::collections::HashMap;\n\nlet mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();\nlet extracted: HashMap<i32, i32> = map.extract_if(|k, _v| k % 2 == 0).collect();\n\nlet mut evens = extracted.keys().copied().collect::<Vec<_>>();\nlet mut odds = map.keys().copied().collect::<Vec<_>>();\nevens.sort();\nodds.sort();\n\nassert_eq!(evens, vec![0, 2, 4, 6]);\nassert_eq!(odds, vec![1, 3, 5, 7]);
Retains only the elements specified by the predicate.
\nIn other words, remove all pairs (k, v)
for which f(&k, &mut v)
returns false
.\nThe elements are visited in unsorted (and unspecified) order.
use std::collections::HashMap;\n\nlet mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();\nmap.retain(|&k, _| k % 2 == 0);\nassert_eq!(map.len(), 4);
In the current implementation, this operation takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.
\nClears the map, removing all key-value pairs. Keeps the allocated memory\nfor reuse.
\nuse std::collections::HashMap;\n\nlet mut a = HashMap::new();\na.insert(1, \"a\");\na.clear();\nassert!(a.is_empty());
Returns a reference to the map’s BuildHasher
.
use std::collections::HashMap;\nuse std::hash::RandomState;\n\nlet hasher = RandomState::new();\nlet map: HashMap<i32, i32> = HashMap::with_hasher(hasher);\nlet hasher: &RandomState = map.hasher();
Reserves capacity for at least additional
more elements to be inserted\nin the HashMap
. The collection may reserve more space to speculatively\navoid frequent reallocations. After calling reserve
,\ncapacity will be greater than or equal to self.len() + additional
.\nDoes nothing if capacity is already sufficient.
Panics if the new allocation size overflows usize
.
use std::collections::HashMap;\nlet mut map: HashMap<&str, i32> = HashMap::new();\nmap.reserve(10);
Tries to reserve capacity for at least additional
more elements to be inserted\nin the HashMap
. The collection may reserve more space to speculatively\navoid frequent reallocations. After calling try_reserve
,\ncapacity will be greater than or equal to self.len() + additional
if\nit returns Ok(())
.\nDoes nothing if capacity is already sufficient.
If the capacity overflows, or the allocator reports a failure, then an error\nis returned.
\nuse std::collections::HashMap;\n\nlet mut map: HashMap<&str, isize> = HashMap::new();\nmap.try_reserve(10).expect(\"why is the test harness OOMing on a handful of bytes?\");
Shrinks the capacity of the map as much as possible. It will drop\ndown as much as possible while maintaining the internal rules\nand possibly leaving some space in accordance with the resize policy.
\nuse std::collections::HashMap;\n\nlet mut map: HashMap<i32, i32> = HashMap::with_capacity(100);\nmap.insert(1, 2);\nmap.insert(3, 4);\nassert!(map.capacity() >= 100);\nmap.shrink_to_fit();\nassert!(map.capacity() >= 2);
Shrinks the capacity of the map with a lower limit. It will drop\ndown no lower than the supplied limit while maintaining the internal rules\nand possibly leaving some space in accordance with the resize policy.
\nIf the current capacity is less than the lower limit, this is a no-op.
\nuse std::collections::HashMap;\n\nlet mut map: HashMap<i32, i32> = HashMap::with_capacity(100);\nmap.insert(1, 2);\nmap.insert(3, 4);\nassert!(map.capacity() >= 100);\nmap.shrink_to(10);\nassert!(map.capacity() >= 10);\nmap.shrink_to(0);\nassert!(map.capacity() >= 2);
Gets the given key’s corresponding entry in the map for in-place manipulation.
\nuse std::collections::HashMap;\n\nlet mut letters = HashMap::new();\n\nfor ch in \"a short treatise on fungi\".chars() {\n letters.entry(ch).and_modify(|counter| *counter += 1).or_insert(1);\n}\n\nassert_eq!(letters[&'s'], 2);\nassert_eq!(letters[&'t'], 3);\nassert_eq!(letters[&'u'], 1);\nassert_eq!(letters.get(&'y'), None);
Returns a reference to the value corresponding to the key.
\nThe key may be any borrowed form of the map’s key type, but\nHash
and Eq
on the borrowed form must match those for\nthe key type.
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nmap.insert(1, \"a\");\nassert_eq!(map.get(&1), Some(&\"a\"));\nassert_eq!(map.get(&2), None);
Returns the key-value pair corresponding to the supplied key.
\nThe supplied key may be any borrowed form of the map’s key type, but\nHash
and Eq
on the borrowed form must match those for\nthe key type.
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nmap.insert(1, \"a\");\nassert_eq!(map.get_key_value(&1), Some((&1, &\"a\")));\nassert_eq!(map.get_key_value(&2), None);
map_many_mut
)Attempts to get mutable references to N
values in the map at once.
Returns an array of length N
with the results of each query. For soundness, at most one\nmutable reference will be returned to any value. None
will be returned if any of the\nkeys are duplicates or missing.
#![feature(map_many_mut)]\nuse std::collections::HashMap;\n\nlet mut libraries = HashMap::new();\nlibraries.insert(\"Bodleian Library\".to_string(), 1602);\nlibraries.insert(\"Athenæum\".to_string(), 1807);\nlibraries.insert(\"Herzogin-Anna-Amalia-Bibliothek\".to_string(), 1691);\nlibraries.insert(\"Library of Congress\".to_string(), 1800);\n\nlet got = libraries.get_many_mut([\n \"Athenæum\",\n \"Library of Congress\",\n]);\nassert_eq!(\n got,\n Some([\n &mut 1807,\n &mut 1800,\n ]),\n);\n\n// Missing keys result in None\nlet got = libraries.get_many_mut([\n \"Athenæum\",\n \"New York Public Library\",\n]);\nassert_eq!(got, None);\n\n// Duplicate keys result in None\nlet got = libraries.get_many_mut([\n \"Athenæum\",\n \"Athenæum\",\n]);\nassert_eq!(got, None);
map_many_mut
)Attempts to get mutable references to N
values in the map at once, without validating that\nthe values are unique.
Returns an array of length N
with the results of each query. None
will be returned if\nany of the keys are missing.
For a safe alternative see get_many_mut
.
Calling this method with overlapping keys is undefined behavior even if the resulting\nreferences are not used.
\n#![feature(map_many_mut)]\nuse std::collections::HashMap;\n\nlet mut libraries = HashMap::new();\nlibraries.insert(\"Bodleian Library\".to_string(), 1602);\nlibraries.insert(\"Athenæum\".to_string(), 1807);\nlibraries.insert(\"Herzogin-Anna-Amalia-Bibliothek\".to_string(), 1691);\nlibraries.insert(\"Library of Congress\".to_string(), 1800);\n\nlet got = libraries.get_many_mut([\n \"Athenæum\",\n \"Library of Congress\",\n]);\nassert_eq!(\n got,\n Some([\n &mut 1807,\n &mut 1800,\n ]),\n);\n\n// Missing keys result in None\nlet got = libraries.get_many_mut([\n \"Athenæum\",\n \"New York Public Library\",\n]);\nassert_eq!(got, None);
Returns true
if the map contains a value for the specified key.
The key may be any borrowed form of the map’s key type, but\nHash
and Eq
on the borrowed form must match those for\nthe key type.
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nmap.insert(1, \"a\");\nassert_eq!(map.contains_key(&1), true);\nassert_eq!(map.contains_key(&2), false);
Returns a mutable reference to the value corresponding to the key.
\nThe key may be any borrowed form of the map’s key type, but\nHash
and Eq
on the borrowed form must match those for\nthe key type.
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nmap.insert(1, \"a\");\nif let Some(x) = map.get_mut(&1) {\n *x = \"b\";\n}\nassert_eq!(map[&1], \"b\");
Inserts a key-value pair into the map.
\nIf the map did not have this key present, None
is returned.
If the map did have this key present, the value is updated, and the old\nvalue is returned. The key is not updated, though; this matters for\ntypes that can be ==
without being identical. See the module-level\ndocumentation for more.
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nassert_eq!(map.insert(37, \"a\"), None);\nassert_eq!(map.is_empty(), false);\n\nmap.insert(37, \"b\");\nassert_eq!(map.insert(37, \"c\"), Some(\"b\"));\nassert_eq!(map[&37], \"c\");
map_try_insert
)Tries to insert a key-value pair into the map, and returns\na mutable reference to the value in the entry.
\nIf the map already had this key present, nothing is updated, and\nan error containing the occupied entry and the value is returned.
\nBasic usage:
\n\n#![feature(map_try_insert)]\n\nuse std::collections::HashMap;\n\nlet mut map = HashMap::new();\nassert_eq!(map.try_insert(37, \"a\").unwrap(), &\"a\");\n\nlet err = map.try_insert(37, \"b\").unwrap_err();\nassert_eq!(err.entry.key(), &37);\nassert_eq!(err.entry.get(), &\"a\");\nassert_eq!(err.value, \"b\");
Removes a key from the map, returning the value at the key if the key\nwas previously in the map.
\nThe key may be any borrowed form of the map’s key type, but\nHash
and Eq
on the borrowed form must match those for\nthe key type.
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nmap.insert(1, \"a\");\nassert_eq!(map.remove(&1), Some(\"a\"));\nassert_eq!(map.remove(&1), None);
Removes a key from the map, returning the stored key and value if the\nkey was previously in the map.
\nThe key may be any borrowed form of the map’s key type, but\nHash
and Eq
on the borrowed form must match those for\nthe key type.
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nmap.insert(1, \"a\");\nassert_eq!(map.remove_entry(&1), Some((1, \"a\")));\nassert_eq!(map.remove(&1), None);
Creates a consuming iterator, that is, one that moves each key-value\npair out of the map in arbitrary order. The map cannot be used after\ncalling this.
\nuse std::collections::HashMap;\n\nlet map = HashMap::from([\n (\"a\", 1),\n (\"b\", 2),\n (\"c\", 3),\n]);\n\n// Not possible with .iter()\nlet vec: Vec<(&str, i32)> = map.into_iter().collect();
Self
but with OldVal
replaced with NewVal
.map_fn
.extend_one
)extend_one
)Inserts all new key-values from the iterator and replaces values with existing\nkeys with new values returned from the iterator.
\nextend_one
)extend_one
)Creates an empty HashMap
.
The hash map is initially created with a capacity of 0, so it will not allocate until it\nis first inserted into.
\nuse std::collections::HashMap;\nlet mut map: HashMap<&str, i32> = HashMap::new();
Creates an empty HashMap
with at least the specified capacity.
The hash map will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the hash map will not allocate.
use std::collections::HashMap;\nlet mut map: HashMap<&str, i32> = HashMap::with_capacity(10);
hash_raw_entry
)Creates a raw entry builder for the HashMap.
\nRaw entries provide the lowest level of control for searching and\nmanipulating a map. They must be manually initialized with a hash and\nthen manually searched. After this, insertions into a vacant entry\nstill require an owned key to be provided.
\nRaw entries are useful for such exotic situations as:
\nBecause raw entries provide much more low-level control, it’s much easier\nto put the HashMap into an inconsistent state which, while memory-safe,\nwill cause the map to produce seemingly random results. Higher-level and\nmore foolproof APIs like entry
should be preferred when possible.
In particular, the hash used to initialize the raw entry must still be\nconsistent with the hash of the key that is ultimately stored in the entry.\nThis is because implementations of HashMap may need to recompute hashes\nwhen resizing, at which point only the keys are available.
\nRaw entries give mutable access to the keys. This must not be used\nto modify how the key would compare or hash, as the map will not re-evaluate\nwhere the key should go, meaning the keys may become “lost” if their\nlocation does not reflect their state. For instance, if you change a key\nso that the map now contains keys which compare equal, search may start\nacting erratically, with two keys randomly masking each other. Implementations\nare free to assume this doesn’t happen (within the limits of memory-safety).
\nhash_raw_entry
)Creates a raw immutable entry builder for the HashMap.
\nRaw entries provide the lowest level of control for searching and\nmanipulating a map. They must be manually initialized with a hash and\nthen manually searched.
\nThis is useful for
\nUnless you are in such a situation, higher-level and more foolproof APIs like\nget
should be preferred.
Immutable raw entries have very limited use; you might instead want raw_entry_mut
.
Creates an empty HashMap
which will use the given hash builder to hash\nkeys.
The created map has the default initial capacity.
\nWarning: hash_builder
is normally randomly generated, and\nis designed to allow HashMaps to be resistant to attacks that\ncause many collisions and very poor performance. Setting it\nmanually using this function can expose a DoS attack vector.
The hash_builder
passed should implement the BuildHasher
trait for\nthe HashMap to be useful, see its documentation for details.
use std::collections::HashMap;\nuse std::hash::RandomState;\n\nlet s = RandomState::new();\nlet mut map = HashMap::with_hasher(s);\nmap.insert(1, 2);
Creates an empty HashMap
with at least the specified capacity, using\nhasher
to hash the keys.
The hash map will be able to hold at least capacity
elements without\nreallocating. This method is allowed to allocate for more elements than\ncapacity
. If capacity
is 0, the hash map will not allocate.
Warning: hasher
is normally randomly generated, and\nis designed to allow HashMaps to be resistant to attacks that\ncause many collisions and very poor performance. Setting it\nmanually using this function can expose a DoS attack vector.
The hasher
passed should implement the BuildHasher
trait for\nthe HashMap to be useful, see its documentation for details.
use std::collections::HashMap;\nuse std::hash::RandomState;\n\nlet s = RandomState::new();\nlet mut map = HashMap::with_capacity_and_hasher(10, s);\nmap.insert(1, 2);
Returns the number of elements the map can hold without reallocating.
\nThis number is a lower bound; the HashMap<K, V>
might be able to hold\nmore, but is guaranteed to be able to hold at least this many.
use std::collections::HashMap;\nlet map: HashMap<i32, i32> = HashMap::with_capacity(100);\nassert!(map.capacity() >= 100);
An iterator visiting all keys in arbitrary order.\nThe iterator element type is &'a K
.
use std::collections::HashMap;\n\nlet map = HashMap::from([\n (\"a\", 1),\n (\"b\", 2),\n (\"c\", 3),\n]);\n\nfor key in map.keys() {\n println!(\"{key}\");\n}
In the current implementation, iterating over keys takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.
\nCreates a consuming iterator visiting all the keys in arbitrary order.\nThe map cannot be used after calling this.\nThe iterator element type is K
.
use std::collections::HashMap;\n\nlet map = HashMap::from([\n (\"a\", 1),\n (\"b\", 2),\n (\"c\", 3),\n]);\n\nlet mut vec: Vec<&str> = map.into_keys().collect();\n// The `IntoKeys` iterator produces keys in arbitrary order, so the\n// keys must be sorted to test them against a sorted array.\nvec.sort_unstable();\nassert_eq!(vec, [\"a\", \"b\", \"c\"]);
In the current implementation, iterating over keys takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.
\nAn iterator visiting all values in arbitrary order.\nThe iterator element type is &'a V
.
use std::collections::HashMap;\n\nlet map = HashMap::from([\n (\"a\", 1),\n (\"b\", 2),\n (\"c\", 3),\n]);\n\nfor val in map.values() {\n println!(\"{val}\");\n}
In the current implementation, iterating over values takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.
\nAn iterator visiting all values mutably in arbitrary order.\nThe iterator element type is &'a mut V
.
use std::collections::HashMap;\n\nlet mut map = HashMap::from([\n (\"a\", 1),\n (\"b\", 2),\n (\"c\", 3),\n]);\n\nfor val in map.values_mut() {\n *val = *val + 10;\n}\n\nfor val in map.values() {\n println!(\"{val}\");\n}
In the current implementation, iterating over values takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.
\nCreates a consuming iterator visiting all the values in arbitrary order.\nThe map cannot be used after calling this.\nThe iterator element type is V
.
use std::collections::HashMap;\n\nlet map = HashMap::from([\n (\"a\", 1),\n (\"b\", 2),\n (\"c\", 3),\n]);\n\nlet mut vec: Vec<i32> = map.into_values().collect();\n// The `IntoValues` iterator produces values in arbitrary order, so\n// the values must be sorted to test them against a sorted array.\nvec.sort_unstable();\nassert_eq!(vec, [1, 2, 3]);
In the current implementation, iterating over values takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.
\nAn iterator visiting all key-value pairs in arbitrary order.\nThe iterator element type is (&'a K, &'a V)
.
use std::collections::HashMap;\n\nlet map = HashMap::from([\n (\"a\", 1),\n (\"b\", 2),\n (\"c\", 3),\n]);\n\nfor (key, val) in map.iter() {\n println!(\"key: {key} val: {val}\");\n}
In the current implementation, iterating over map takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.
\nAn iterator visiting all key-value pairs in arbitrary order,\nwith mutable references to the values.\nThe iterator element type is (&'a K, &'a mut V)
.
use std::collections::HashMap;\n\nlet mut map = HashMap::from([\n (\"a\", 1),\n (\"b\", 2),\n (\"c\", 3),\n]);\n\n// Update all values\nfor (_, val) in map.iter_mut() {\n *val *= 2;\n}\n\nfor (key, val) in &map {\n println!(\"key: {key} val: {val}\");\n}
In the current implementation, iterating over map takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.
\nReturns the number of elements in the map.
\nuse std::collections::HashMap;\n\nlet mut a = HashMap::new();\nassert_eq!(a.len(), 0);\na.insert(1, \"a\");\nassert_eq!(a.len(), 1);
Returns true
if the map contains no elements.
use std::collections::HashMap;\n\nlet mut a = HashMap::new();\nassert!(a.is_empty());\na.insert(1, \"a\");\nassert!(!a.is_empty());
Clears the map, returning all key-value pairs as an iterator. Keeps the\nallocated memory for reuse.
\nIf the returned iterator is dropped before being fully consumed, it\ndrops the remaining key-value pairs. The returned iterator keeps a\nmutable borrow on the map to optimize its implementation.
\nuse std::collections::HashMap;\n\nlet mut a = HashMap::new();\na.insert(1, \"a\");\na.insert(2, \"b\");\n\nfor (k, v) in a.drain().take(1) {\n assert!(k == 1 || k == 2);\n assert!(v == \"a\" || v == \"b\");\n}\n\nassert!(a.is_empty());
hash_extract_if
)Creates an iterator which uses a closure to determine if an element should be removed.
\nIf the closure returns true, the element is removed from the map and yielded.\nIf the closure returns false, or panics, the element remains in the map and will not be\nyielded.
\nNote that extract_if
lets you mutate every value in the filter closure, regardless of\nwhether you choose to keep or remove it.
If the returned ExtractIf
is not exhausted, e.g. because it is dropped without iterating\nor the iteration short-circuits, then the remaining elements will be retained.\nUse retain
with a negated predicate if you do not need the returned iterator.
Splitting a map into even and odd keys, reusing the original map:
\n\n#![feature(hash_extract_if)]\nuse std::collections::HashMap;\n\nlet mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x)).collect();\nlet extracted: HashMap<i32, i32> = map.extract_if(|k, _v| k % 2 == 0).collect();\n\nlet mut evens = extracted.keys().copied().collect::<Vec<_>>();\nlet mut odds = map.keys().copied().collect::<Vec<_>>();\nevens.sort();\nodds.sort();\n\nassert_eq!(evens, vec![0, 2, 4, 6]);\nassert_eq!(odds, vec![1, 3, 5, 7]);
Retains only the elements specified by the predicate.
\nIn other words, remove all pairs (k, v)
for which f(&k, &mut v)
returns false
.\nThe elements are visited in unsorted (and unspecified) order.
use std::collections::HashMap;\n\nlet mut map: HashMap<i32, i32> = (0..8).map(|x| (x, x*10)).collect();\nmap.retain(|&k, _| k % 2 == 0);\nassert_eq!(map.len(), 4);
In the current implementation, this operation takes O(capacity) time\ninstead of O(len) because it internally visits empty buckets too.
\nClears the map, removing all key-value pairs. Keeps the allocated memory\nfor reuse.
\nuse std::collections::HashMap;\n\nlet mut a = HashMap::new();\na.insert(1, \"a\");\na.clear();\nassert!(a.is_empty());
Returns a reference to the map’s BuildHasher
.
use std::collections::HashMap;\nuse std::hash::RandomState;\n\nlet hasher = RandomState::new();\nlet map: HashMap<i32, i32> = HashMap::with_hasher(hasher);\nlet hasher: &RandomState = map.hasher();
Reserves capacity for at least additional
more elements to be inserted\nin the HashMap
. The collection may reserve more space to speculatively\navoid frequent reallocations. After calling reserve
,\ncapacity will be greater than or equal to self.len() + additional
.\nDoes nothing if capacity is already sufficient.
Panics if the new allocation size overflows usize
.
use std::collections::HashMap;\nlet mut map: HashMap<&str, i32> = HashMap::new();\nmap.reserve(10);
Tries to reserve capacity for at least additional
more elements to be inserted\nin the HashMap
. The collection may reserve more space to speculatively\navoid frequent reallocations. After calling try_reserve
,\ncapacity will be greater than or equal to self.len() + additional
if\nit returns Ok(())
.\nDoes nothing if capacity is already sufficient.
If the capacity overflows, or the allocator reports a failure, then an error\nis returned.
\nuse std::collections::HashMap;\n\nlet mut map: HashMap<&str, isize> = HashMap::new();\nmap.try_reserve(10).expect(\"why is the test harness OOMing on a handful of bytes?\");
Shrinks the capacity of the map as much as possible. It will drop\ndown as much as possible while maintaining the internal rules\nand possibly leaving some space in accordance with the resize policy.
\nuse std::collections::HashMap;\n\nlet mut map: HashMap<i32, i32> = HashMap::with_capacity(100);\nmap.insert(1, 2);\nmap.insert(3, 4);\nassert!(map.capacity() >= 100);\nmap.shrink_to_fit();\nassert!(map.capacity() >= 2);
Shrinks the capacity of the map with a lower limit. It will drop\ndown no lower than the supplied limit while maintaining the internal rules\nand possibly leaving some space in accordance with the resize policy.
\nIf the current capacity is less than the lower limit, this is a no-op.
\nuse std::collections::HashMap;\n\nlet mut map: HashMap<i32, i32> = HashMap::with_capacity(100);\nmap.insert(1, 2);\nmap.insert(3, 4);\nassert!(map.capacity() >= 100);\nmap.shrink_to(10);\nassert!(map.capacity() >= 10);\nmap.shrink_to(0);\nassert!(map.capacity() >= 2);
Gets the given key’s corresponding entry in the map for in-place manipulation.
\nuse std::collections::HashMap;\n\nlet mut letters = HashMap::new();\n\nfor ch in \"a short treatise on fungi\".chars() {\n letters.entry(ch).and_modify(|counter| *counter += 1).or_insert(1);\n}\n\nassert_eq!(letters[&'s'], 2);\nassert_eq!(letters[&'t'], 3);\nassert_eq!(letters[&'u'], 1);\nassert_eq!(letters.get(&'y'), None);
Returns a reference to the value corresponding to the key.
\nThe key may be any borrowed form of the map’s key type, but\nHash
and Eq
on the borrowed form must match those for\nthe key type.
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nmap.insert(1, \"a\");\nassert_eq!(map.get(&1), Some(&\"a\"));\nassert_eq!(map.get(&2), None);
Returns the key-value pair corresponding to the supplied key.
\nThe supplied key may be any borrowed form of the map’s key type, but\nHash
and Eq
on the borrowed form must match those for\nthe key type.
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nmap.insert(1, \"a\");\nassert_eq!(map.get_key_value(&1), Some((&1, &\"a\")));\nassert_eq!(map.get_key_value(&2), None);
map_many_mut
)Attempts to get mutable references to N
values in the map at once.
Returns an array of length N
with the results of each query. For soundness, at most one\nmutable reference will be returned to any value. None
will be returned if any of the\nkeys are duplicates or missing.
#![feature(map_many_mut)]\nuse std::collections::HashMap;\n\nlet mut libraries = HashMap::new();\nlibraries.insert(\"Bodleian Library\".to_string(), 1602);\nlibraries.insert(\"Athenæum\".to_string(), 1807);\nlibraries.insert(\"Herzogin-Anna-Amalia-Bibliothek\".to_string(), 1691);\nlibraries.insert(\"Library of Congress\".to_string(), 1800);\n\nlet got = libraries.get_many_mut([\n \"Athenæum\",\n \"Library of Congress\",\n]);\nassert_eq!(\n got,\n Some([\n &mut 1807,\n &mut 1800,\n ]),\n);\n\n// Missing keys result in None\nlet got = libraries.get_many_mut([\n \"Athenæum\",\n \"New York Public Library\",\n]);\nassert_eq!(got, None);\n\n// Duplicate keys result in None\nlet got = libraries.get_many_mut([\n \"Athenæum\",\n \"Athenæum\",\n]);\nassert_eq!(got, None);
map_many_mut
)Attempts to get mutable references to N
values in the map at once, without validating that\nthe values are unique.
Returns an array of length N
with the results of each query. None
will be returned if\nany of the keys are missing.
For a safe alternative see get_many_mut
.
Calling this method with overlapping keys is undefined behavior even if the resulting\nreferences are not used.
\n#![feature(map_many_mut)]\nuse std::collections::HashMap;\n\nlet mut libraries = HashMap::new();\nlibraries.insert(\"Bodleian Library\".to_string(), 1602);\nlibraries.insert(\"Athenæum\".to_string(), 1807);\nlibraries.insert(\"Herzogin-Anna-Amalia-Bibliothek\".to_string(), 1691);\nlibraries.insert(\"Library of Congress\".to_string(), 1800);\n\nlet got = libraries.get_many_mut([\n \"Athenæum\",\n \"Library of Congress\",\n]);\nassert_eq!(\n got,\n Some([\n &mut 1807,\n &mut 1800,\n ]),\n);\n\n// Missing keys result in None\nlet got = libraries.get_many_mut([\n \"Athenæum\",\n \"New York Public Library\",\n]);\nassert_eq!(got, None);
Returns true
if the map contains a value for the specified key.
The key may be any borrowed form of the map’s key type, but\nHash
and Eq
on the borrowed form must match those for\nthe key type.
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nmap.insert(1, \"a\");\nassert_eq!(map.contains_key(&1), true);\nassert_eq!(map.contains_key(&2), false);
Returns a mutable reference to the value corresponding to the key.
\nThe key may be any borrowed form of the map’s key type, but\nHash
and Eq
on the borrowed form must match those for\nthe key type.
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nmap.insert(1, \"a\");\nif let Some(x) = map.get_mut(&1) {\n *x = \"b\";\n}\nassert_eq!(map[&1], \"b\");
Inserts a key-value pair into the map.
\nIf the map did not have this key present, None
is returned.
If the map did have this key present, the value is updated, and the old\nvalue is returned. The key is not updated, though; this matters for\ntypes that can be ==
without being identical. See the module-level\ndocumentation for more.
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nassert_eq!(map.insert(37, \"a\"), None);\nassert_eq!(map.is_empty(), false);\n\nmap.insert(37, \"b\");\nassert_eq!(map.insert(37, \"c\"), Some(\"b\"));\nassert_eq!(map[&37], \"c\");
map_try_insert
)Tries to insert a key-value pair into the map, and returns\na mutable reference to the value in the entry.
\nIf the map already had this key present, nothing is updated, and\nan error containing the occupied entry and the value is returned.
\nBasic usage:
\n\n#![feature(map_try_insert)]\n\nuse std::collections::HashMap;\n\nlet mut map = HashMap::new();\nassert_eq!(map.try_insert(37, \"a\").unwrap(), &\"a\");\n\nlet err = map.try_insert(37, \"b\").unwrap_err();\nassert_eq!(err.entry.key(), &37);\nassert_eq!(err.entry.get(), &\"a\");\nassert_eq!(err.value, \"b\");
Removes a key from the map, returning the value at the key if the key\nwas previously in the map.
\nThe key may be any borrowed form of the map’s key type, but\nHash
and Eq
on the borrowed form must match those for\nthe key type.
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nmap.insert(1, \"a\");\nassert_eq!(map.remove(&1), Some(\"a\"));\nassert_eq!(map.remove(&1), None);
Removes a key from the map, returning the stored key and value if the\nkey was previously in the map.
\nThe key may be any borrowed form of the map’s key type, but\nHash
and Eq
on the borrowed form must match those for\nthe key type.
use std::collections::HashMap;\n\nlet mut map = HashMap::new();\nmap.insert(1, \"a\");\nassert_eq!(map.remove_entry(&1), Some((1, \"a\")));\nassert_eq!(map.remove(&1), None);
Creates a consuming iterator, that is, one that moves each key-value\npair out of the map in arbitrary order. The map cannot be used after\ncalling this.
\nuse std::collections::HashMap;\n\nlet map = HashMap::from([\n (\"a\", 1),\n (\"b\", 2),\n (\"c\", 3),\n]);\n\n// Not possible with .iter()\nlet vec: Vec<(&str, i32)> = map.into_iter().collect();
Self
but with OldVal
replaced with NewVal
.map_fn
.