Struct HashMap
struct HashMap<K, V, S = crate::DefaultHashBuilder, A: Allocator = self::inner::Global> { ... }
A hash map implemented with quadratic probing and SIMD lookup.
The default hashing algorithm is currently foldhash, though this is
subject to change at any point in the future. This hash function is very
fast for all types of keys, but this algorithm will typically not protect
against attacks such as HashDoS.
The hashing algorithm can be replaced on a per-HashMap basis using the
default, with_hasher, and with_capacity_and_hasher methods. Many
alternative algorithms are available on crates.io, such as the fnv crate.
It is required that the keys implement the Eq and Hash traits, although
this can frequently be achieved by using #[derive(PartialEq, Eq, Hash)].
If you implement these yourself, it is important that the following
property holds:
k1 == k2 -> hash(k1) == hash(k2)
In other words, if two keys are equal, their hashes must be equal.
It is a logic error for a key to be modified in such a way that the key's
hash, as determined by the Hash trait, or its equality, as determined by
the Eq trait, changes while it is in the map. This is normally only
possible through Cell, RefCell, global state, I/O, or unsafe code.
It is also a logic error for the Hash implementation of a key to panic.
This is generally only possible if the trait is implemented manually. If a
panic does occur then the contents of the HashMap may become corrupted and
some items may be dropped from the table.
Examples
use HashMap;
// Type inference lets us omit an explicit type signature (which
// would be `HashMap<String, String>` in this example).
let mut book_reviews = new;
// Review some books.
book_reviews.insert;
book_reviews.insert;
book_reviews.insert;
book_reviews.insert;
// Check for a specific one.
// When collections store owned values (String), they can still be
// queried using references (&str).
if !book_reviews.contains_key
// oops, this review has a lot of spelling mistakes, let's delete it.
book_reviews.remove;
// Look up the values associated with some keys.
let to_find = ;
for &book in &to_find
// Look up the value for a key (will panic if the key is not found).
println!;
// Iterate over everything.
for in &book_reviews
HashMap also implements an Entry API, which allows
for more complex methods of getting, setting, updating and removing keys and
their values:
use HashMap;
// type inference lets us omit an explicit type signature (which
// would be `HashMap<&str, u8>` in this example).
let mut player_stats = new;
// insert a key only if it doesn't already exist
player_stats.entry.or_insert;
// insert a key using a function that provides a new value only if it
// doesn't already exist
player_stats.entry.or_insert_with;
// update a key, guarding against the key possibly not being set
let stat = player_stats.entry.or_insert;
*stat += random_stat_buff;
The easiest way to use HashMap with a custom key type is to derive Eq and Hash.
We must also derive PartialEq.
use HashMap;
// Use a HashMap to store the vikings' health points.
let mut vikings = new;
vikings.insert;
vikings.insert;
vikings.insert;
// Use derived implementation to print the status of the vikings.
for in &vikings
A HashMap with fixed list of elements can be initialized from an array:
use HashMap;
let timber_resources: =
.into_iter.collect;
// use the values stored in map
Implementations
impl<K, V, S> HashMap<K, V, S>
const fn with_hasher(hash_builder: S) -> SelfCreates an empty
HashMapwhich will use the given hash builder to hash keys.The hash map is initially created with a capacity of 0, so it will not allocate until it is first inserted into.
HashDoS resistance
The
hash_buildernormally use a fixed key by default and that does not allow theHashMapto be protected against attacks such asHashDoS. Users who require HashDoS resistance should explicitly usestd::collections::hash_map::RandomStateas the hasher when creating aHashMap.The
hash_builderpassed should implement theBuildHashertrait for theHashMapto be useful, see its documentation for details.Examples
use HashMap; use DefaultHashBuilder; let s = default; let mut map = with_hasher; assert_eq!; assert_eq!; map.insert;fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> SelfCreates an empty
HashMapwith the specified capacity, usinghash_builderto hash the keys.The hash map will be able to hold at least
capacityelements without reallocating. Ifcapacityis 0, the hash map will not allocate.HashDoS resistance
The
hash_buildernormally use a fixed key by default and that does not allow theHashMapto be protected against attacks such asHashDoS. Users who require HashDoS resistance should explicitly usestd::collections::hash_map::RandomStateas the hasher when creating aHashMap.The
hash_builderpassed should implement theBuildHashertrait for theHashMapto be useful, see its documentation for details.Examples
use HashMap; use DefaultHashBuilder; let s = default; let mut map = with_capacity_and_hasher; assert_eq!; assert!; map.insert;
impl<K, V, S, A> HashMap<K, V, S, A>
fn reserve(self: &mut Self, additional: usize)Reserves capacity for at least
additionalmore elements to be inserted in theHashMap. The collection may reserve more space to avoid frequent reallocations.Panics
Panics if the new capacity exceeds
isize::MAXbytes andabortthe program in case of allocation error. Usetry_reserveinstead if you want to handle memory allocation failure.Examples
use HashMap; let mut map: = new; // Map is empty and doesn't allocate memory assert_eq!; map.reserve; // And now map can hold at least 10 elements assert!;fn try_reserve(self: &mut Self, additional: usize) -> Result<(), TryReserveError>Tries to reserve capacity for at least
additionalmore elements to be inserted in the givenHashMap<K,V>. The collection may reserve more space to avoid frequent reallocations.Errors
If the capacity overflows, or the allocator reports a failure, then an error is returned.
Examples
use HashMap; let mut map: = new; // Map is empty and doesn't allocate memory assert_eq!; map.try_reserve.expect; // And now map can hold at least 10 elements assert!;If the capacity overflows, or the allocator reports a failure, then an error is returned:
# #fn shrink_to_fit(self: &mut Self)Shrinks the capacity of the map as much as possible. It will drop down as much as possible while maintaining the internal rules and possibly leaving some space in accordance with the resize policy.
Examples
use HashMap; let mut map: = with_capacity; map.insert; map.insert; assert!; map.shrink_to_fit; assert!;fn shrink_to(self: &mut Self, min_capacity: usize)Shrinks the capacity of the map with a lower limit. It will drop down no lower than the supplied limit while maintaining the internal rules and possibly leaving some space in accordance with the resize policy.
This function does nothing if the current capacity is smaller than the supplied minimum capacity.
Examples
use HashMap; let mut map: = with_capacity; map.insert; map.insert; assert!; map.shrink_to; assert!; map.shrink_to; assert!; map.shrink_to; assert!;fn entry(self: &mut Self, key: K) -> Entry<'_, K, V, S, A>Gets the given key's corresponding entry in the map for in-place manipulation.
Examples
use HashMap; let mut letters = new; for ch in "a short treatise on fungi".chars assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn entry_ref<'a, 'b, Q>(self: &'a mut Self, key: &'b Q) -> EntryRef<'a, 'b, K, Q, V, S, A> where Q: Hash + Equivalent<K> + ?SizedGets the given key's corresponding entry by reference in the map for in-place manipulation.
Examples
use HashMap; let mut words: = new; let source = ; for in source.iter.enumerate assert_eq!; assert_eq!;fn get<Q>(self: &Self, k: &Q) -> Option<&V> where Q: Hash + Equivalent<K> + ?SizedReturns a reference to the value corresponding to the key.
The key may be any borrowed form of the map's key type, but
HashandEqon the borrowed form must match those for the key type.Examples
use HashMap; let mut map = new; map.insert; assert_eq!; assert_eq!;fn get_key_value<Q>(self: &Self, k: &Q) -> Option<(&K, &V)> where Q: Hash + Equivalent<K> + ?SizedReturns the key-value pair corresponding to the supplied key.
The supplied key may be any borrowed form of the map's key type, but
HashandEqon the borrowed form must match those for the key type.Examples
use HashMap; let mut map = new; map.insert; assert_eq!; assert_eq!;fn get_key_value_mut<Q>(self: &mut Self, k: &Q) -> Option<(&K, &mut V)> where Q: Hash + Equivalent<K> + ?SizedReturns the key-value pair corresponding to the supplied key, with a mutable reference to value.
The supplied key may be any borrowed form of the map's key type, but
HashandEqon the borrowed form must match those for the key type.Examples
use HashMap; let mut map = new; map.insert; let = map.get_key_value_mut.unwrap; assert_eq!; assert_eq!; *v = "b"; assert_eq!; assert_eq!;fn contains_key<Q>(self: &Self, k: &Q) -> bool where Q: Hash + Equivalent<K> + ?SizedReturns
trueif the map contains a value for the specified key.The key may be any borrowed form of the map's key type, but
HashandEqon the borrowed form must match those for the key type.Examples
use HashMap; let mut map = new; map.insert; assert_eq!; assert_eq!;fn get_mut<Q>(self: &mut Self, k: &Q) -> Option<&mut V> where Q: Hash + Equivalent<K> + ?SizedReturns a mutable reference to the value corresponding to the key.
The key may be any borrowed form of the map's key type, but
HashandEqon the borrowed form must match those for the key type.Examples
use HashMap; let mut map = new; map.insert; if let Some = map.get_mut assert_eq!; assert_eq!;fn get_many_mut<Q, N: usize>(self: &mut Self, ks: [&Q; N]) -> [Option<&mut V>; N] where Q: Hash + Equivalent<K> + ?SizedAttempts to get mutable references to
Nvalues in the map at once.Returns an array of length
Nwith the results of each query. For soundness, at most one mutable reference will be returned to any value.Nonewill be used if the key is missing.Panics
Panics if any keys are overlapping.
Examples
use HashMap; let mut libraries = new; libraries.insert; libraries.insert; libraries.insert; libraries.insert; // Get Athenæum and Bodleian Library let = libraries.get_many_mut else ; // Assert values of Athenæum and Library of Congress let got = libraries.get_many_mut; assert_eq!; // Missing keys result in None let got = libraries.get_many_mut; assert_eq!;use hashbrown::HashMap; let mut libraries = HashMap::new(); libraries.insert("Athenæum".to_string(), 1807); // Duplicate keys panic! let got = libraries.get_many_mut([ "Athenæum", "Athenæum", ]);unsafe fn get_many_unchecked_mut<Q, N: usize>(self: &mut Self, ks: [&Q; N]) -> [Option<&mut V>; N] where Q: Hash + Equivalent<K> + ?SizedAttempts to get mutable references to
Nvalues in the map at once, without validating that the values are unique.Returns an array of length
Nwith the results of each query.Nonewill be used if the key is missing.For a safe alternative see
get_many_mut.Safety
Calling this method with overlapping keys is undefined behavior even if the resulting references are not used.
Examples
use HashMap; let mut libraries = new; libraries.insert; libraries.insert; libraries.insert; libraries.insert; // SAFETY: The keys do not overlap. let = else ; // SAFETY: The keys do not overlap. let got = unsafe ; assert_eq!; // SAFETY: The keys do not overlap. let got = unsafe ; // Missing keys result in None assert_eq!;fn get_many_key_value_mut<Q, N: usize>(self: &mut Self, ks: [&Q; N]) -> [Option<(&K, &mut V)>; N] where Q: Hash + Equivalent<K> + ?SizedAttempts to get mutable references to
Nvalues in the map at once, with immutable references to the corresponding keys.Returns an array of length
Nwith the results of each query. For soundness, at most one mutable reference will be returned to any value.Nonewill be used if the key is missing.Panics
Panics if any keys are overlapping.
Examples
use HashMap; let mut libraries = new; libraries.insert; libraries.insert; libraries.insert; libraries.insert; let got = libraries.get_many_key_value_mut; assert_eq!; // Missing keys result in None let got = libraries.get_many_key_value_mut; assert_eq!;use hashbrown::HashMap; let mut libraries = HashMap::new(); libraries.insert("Bodleian Library".to_string(), 1602); libraries.insert("Herzogin-Anna-Amalia-Bibliothek".to_string(), 1691); // Duplicate keys result in panic! let got = libraries.get_many_key_value_mut([ "Bodleian Library", "Herzogin-Anna-Amalia-Bibliothek", "Herzogin-Anna-Amalia-Bibliothek", ]);unsafe fn get_many_key_value_unchecked_mut<Q, N: usize>(self: &mut Self, ks: [&Q; N]) -> [Option<(&K, &mut V)>; N] where Q: Hash + Equivalent<K> + ?SizedAttempts to get mutable references to
Nvalues in the map at once, with immutable references to the corresponding keys, without validating that the values are unique.Returns an array of length
Nwith the results of each query.Nonewill be returned if any of the keys are missing.For a safe alternative see
get_many_key_value_mut.Safety
Calling this method with overlapping keys is undefined behavior even if the resulting references are not used.
Examples
use HashMap; let mut libraries = new; libraries.insert; libraries.insert; libraries.insert; libraries.insert; let got = libraries.get_many_key_value_mut; assert_eq!; // Missing keys result in None let got = libraries.get_many_key_value_mut; assert_eq!;fn insert(self: &mut Self, k: K, v: V) -> Option<V>Inserts a key-value pair into the map.
If the map did not have this key present,
Noneis returned.If the map did have this key present, the value is updated, and the old value is returned. The key is not updated, though; this matters for types that can be
==without being identical. See thestd::collectionsmodule-level documentation for more.Examples
use HashMap; let mut map = new; assert_eq!; assert_eq!; map.insert; assert_eq!; assert_eq!;unsafe fn insert_unique_unchecked(self: &mut Self, k: K, v: V) -> (&K, &mut V)Insert a key-value pair into the map without checking if the key already exists in the map.
This operation is faster than regular insert, because it does not perform lookup before insertion.
This operation is useful during initial population of the map. For example, when constructing a map from another map, we know that keys are unique.
Returns a reference to the key and value just inserted.
Safety
This operation is safe if a key does not exist in the map.
However, if a key exists in the map already, the behavior is unspecified: this operation may panic, loop forever, or any following operation with the map may panic, loop forever or return arbitrary result.
That said, this operation (and following operations) are guaranteed to not violate memory safety.
However this operation is still unsafe because the resulting
HashMapmay be passed to unsafe code which does expect the map to behave correctly, and would cause unsoundness as a result.Examples
use HashMap; let mut map1 = new; assert_eq!; assert_eq!; assert_eq!; assert_eq!; let mut map2 = new; for in map1.into_iter let = unsafe ; assert_eq!; assert_eq!; *value = "e"; assert_eq!; assert_eq!; assert_eq!; assert_eq!; assert_eq!;fn try_insert(self: &mut Self, key: K, value: V) -> Result<&mut V, OccupiedError<'_, K, V, S, A>>Tries to insert a key-value pair into the map, and returns a mutable reference to the value in the entry.
Errors
If the map already had this key present, nothing is updated, and an error containing the occupied entry and the value is returned.
Examples
Basic usage:
use HashMap; use OccupiedError; let mut map = new; assert_eq!; match map.try_insertfn remove<Q>(self: &mut Self, k: &Q) -> Option<V> where Q: Hash + Equivalent<K> + ?SizedRemoves a key from the map, returning the value at the key if the key was previously in the map. Keeps the allocated memory for reuse.
The key may be any borrowed form of the map's key type, but
HashandEqon the borrowed form must match those for the key type.Examples
use HashMap; let mut map = new; // The map is empty assert!; map.insert; assert_eq!; assert_eq!; // Now map holds none elements assert!;fn remove_entry<Q>(self: &mut Self, k: &Q) -> Option<(K, V)> where Q: Hash + Equivalent<K> + ?SizedRemoves a key from the map, returning the stored key and value if the key was previously in the map. Keeps the allocated memory for reuse.
The key may be any borrowed form of the map's key type, but
HashandEqon the borrowed form must match those for the key type.Examples
use HashMap; let mut map = new; // The map is empty assert!; map.insert; assert_eq!; assert_eq!; // Now map hold none elements assert!;fn allocation_size(self: &Self) -> usizeReturns the total amount of memory allocated internally by the hash set, in bytes.
The returned number is informational only. It is intended to be primarily used for memory profiling.
impl<K, V, S, A: Allocator> HashMap<K, V, S, A>
fn allocator(self: &Self) -> &AReturns a reference to the underlying allocator.
const fn with_hasher_in(hash_builder: S, alloc: A) -> SelfCreates an empty
HashMapwhich will use the given hash builder to hash keys. It will be allocated with the given allocator.The hash map is initially created with a capacity of 0, so it will not allocate until it is first inserted into.
HashDoS resistance
The
hash_buildernormally use a fixed key by default and that does not allow theHashMapto be protected against attacks such asHashDoS. Users who require HashDoS resistance should explicitly usestd::collections::hash_map::RandomStateas the hasher when creating aHashMap.Examples
use HashMap; use DefaultHashBuilder; let s = default; let mut map = with_hasher; map.insert;fn with_capacity_and_hasher_in(capacity: usize, hash_builder: S, alloc: A) -> SelfCreates an empty
HashMapwith the specified capacity, usinghash_builderto hash the keys. It will be allocated with the given allocator.The hash map will be able to hold at least
capacityelements without reallocating. Ifcapacityis 0, the hash map will not allocate.HashDoS resistance
The
hash_buildernormally use a fixed key by default and that does not allow theHashMapto be protected against attacks such asHashDoS. Users who require HashDoS resistance should explicitly usestd::collections::hash_map::RandomStateas the hasher when creating aHashMap.Examples
use HashMap; use DefaultHashBuilder; let s = default; let mut map = with_capacity_and_hasher; map.insert;fn hasher(self: &Self) -> &SReturns a reference to the map's
BuildHasher.Examples
use HashMap; use DefaultHashBuilder; let hasher = default; let map: = with_hasher; let hasher: &DefaultHashBuilder = map.hasher;fn capacity(self: &Self) -> usizeReturns the number of elements the map can hold without reallocating.
This number is a lower bound; the
HashMap<K, V>might be able to hold more, but is guaranteed to be able to hold at least this many.Examples
use HashMap; let map: = with_capacity; assert_eq!; assert!;fn keys(self: &Self) -> Keys<'_, K, V>An iterator visiting all keys in arbitrary order. The iterator element type is
&'a K.Examples
use HashMap; let mut map = new; map.insert; map.insert; map.insert; assert_eq!; let mut vec: = Vecnew; for key in map.keys // The `Keys` iterator produces keys in arbitrary order, so the // keys must be sorted to test them against a sorted array. vec.sort_unstable; assert_eq!; assert_eq!;fn values(self: &Self) -> Values<'_, K, V>An iterator visiting all values in arbitrary order. The iterator element type is
&'a V.Examples
use HashMap; let mut map = new; map.insert; map.insert; map.insert; assert_eq!; let mut vec: = Vecnew; for val in map.values // The `Values` iterator produces values in arbitrary order, so the // values must be sorted to test them against a sorted array. vec.sort_unstable; assert_eq!; assert_eq!;fn values_mut(self: &mut Self) -> ValuesMut<'_, K, V>An iterator visiting all values mutably in arbitrary order. The iterator element type is
&'a mut V.Examples
use HashMap; let mut map = new; map.insert; map.insert; map.insert; for val in map.values_mut assert_eq!; let mut vec: = Vecnew; for val in map.values // The `Values` iterator produces values in arbitrary order, so the // values must be sorted to test them against a sorted array. vec.sort_unstable; assert_eq!; assert_eq!;fn iter(self: &Self) -> Iter<'_, K, V>An iterator visiting all key-value pairs in arbitrary order. The iterator element type is
(&'a K, &'a V).Examples
use HashMap; let mut map = new; map.insert; map.insert; map.insert; assert_eq!; let mut vec: = Vecnew; for in map.iter // The `Iter` iterator produces items in arbitrary order, so the // items must be sorted to test them against a sorted array. vec.sort_unstable; assert_eq!; assert_eq!;fn iter_mut(self: &mut Self) -> IterMut<'_, K, V>An iterator visiting all key-value pairs in arbitrary order, with mutable references to the values. The iterator element type is
(&'a K, &'a mut V).Examples
use HashMap; let mut map = new; map.insert; map.insert; map.insert; // Update all values for in map.iter_mut assert_eq!; let mut vec: = Vecnew; for in &map // The `Iter` iterator produces items in arbitrary order, so the // items must be sorted to test them against a sorted array. vec.sort_unstable; assert_eq!; assert_eq!;fn len(self: &Self) -> usizeReturns the number of elements in the map.
Examples
use HashMap; let mut a = new; assert_eq!; a.insert; assert_eq!;fn is_empty(self: &Self) -> boolReturns
trueif the map contains no elements.Examples
use HashMap; let mut a = new; assert!; a.insert; assert!;fn drain(self: &mut Self) -> Drain<'_, K, V, A>Clears the map, returning all key-value pairs as an iterator. Keeps the allocated memory for reuse.
If the returned iterator is dropped before being fully consumed, it drops the remaining key-value pairs. The returned iterator keeps a mutable borrow on the vector to optimize its implementation.
Examples
use HashMap; let mut a = new; a.insert; a.insert; let capacity_before_drain = a.capacity; for in a.drain.take // As we can see, the map is empty and contains no element. assert!; // But map capacity is equal to old one. assert_eq!; let mut a = new; a.insert; a.insert; // But the map is empty even if we do not use Drain iterator. assert!;fn retain<F>(self: &mut Self, f: F) where F: FnMut(&K, &mut V) -> boolRetains only the elements specified by the predicate. Keeps the allocated memory for reuse.
In other words, remove all pairs
(k, v)such thatf(&k, &mut v)returnsfalse. The elements are visited in unsorted (and unspecified) order.Examples
use HashMap; let mut map: = .map.collect; assert_eq!; map.retain; // We can see, that the number of elements inside map is changed. assert_eq!; let mut vec: = map.iter.map.collect; vec.sort_unstable; assert_eq!;fn extract_if<F>(self: &mut Self, f: F) -> ExtractIf<'_, K, V, F, A> where F: FnMut(&K, &mut V) -> boolDrains elements which are true under the given predicate, and returns an iterator over the removed items.
In other words, move all pairs
(k, v)such thatf(&k, &mut v)returnstrueout into another iterator.Note that
extract_iflets you mutate every value in the filter closure, regardless of whether you choose to keep or remove it.If the returned
ExtractIfis not exhausted, e.g. because it is dropped without iterating or the iteration short-circuits, then the remaining elements will be retained. Useretain()with a negated predicate if you do not need the returned iterator.Keeps the allocated memory for reuse.
Examples
use HashMap; let mut map: = .map.collect; let drained: = map.extract_if.collect; let mut evens = drained.keys.cloned.; let mut odds = map.keys.cloned.; evens.sort; odds.sort; assert_eq!; assert_eq!; let mut map: = .map.collect; // ExtractIf was not exhausted, therefore no elements were drained. assert_eq!;fn clear(self: &mut Self)Clears the map, removing all key-value pairs. Keeps the allocated memory for reuse.
Examples
use HashMap; let mut a = new; a.insert; let capacity_before_clear = a.capacity; a.clear; // Map is empty. assert!; // But map capacity is equal to old one. assert_eq!;fn into_keys(self: Self) -> IntoKeys<K, V, A>Creates a consuming iterator visiting all the keys in arbitrary order. The map cannot be used after calling this. The iterator element type is
K.Examples
use HashMap; let mut map = new; map.insert; map.insert; map.insert; let mut vec: = map.into_keys.collect; // The `IntoKeys` iterator produces keys in arbitrary order, so the // keys must be sorted to test them against a sorted array. vec.sort_unstable; assert_eq!;fn into_values(self: Self) -> IntoValues<K, V, A>Creates a consuming iterator visiting all the values in arbitrary order. The map cannot be used after calling this. The iterator element type is
V.Examples
use HashMap; let mut map = new; map.insert; map.insert; map.insert; let mut vec: = map.into_values.collect; // The `IntoValues` iterator produces values in arbitrary order, so // the values must be sorted to test them against a sorted array. vec.sort_unstable; assert_eq!;
impl<'a, K, V, S, A> Extend for HashMap<K, V, S, A>
fn extend<T: IntoIterator<Item = (&'a K, &'a V)>>(self: &mut Self, iter: T)Inserts all new key-values from the iterator to existing
HashMap<K, V, S, A>. Replace values with existing keys with new values returned from the iterator. The keys and values must implementCopytrait.Examples
use HashMap; let mut map = new; map.insert; let arr = ; let some_iter = arr.iter.map; map.extend; // Replace values with existing keys with new values returned from the iterator. // So that the map.get(&1) doesn't return Some(&100). assert_eq!; let some_vec: = vec!; map.extend; let some_arr = ; map.extend; // You can also extend from another HashMap let mut new_map = new; new_map.extend; assert_eq!; let mut vec: = new_map.into_iter.collect; // The `IntoIter` iterator produces items in arbitrary order, so the // items must be sorted to test them against a sorted array. vec.sort_unstable; assert_eq!;
impl<'a, K, V, S, A> Extend for HashMap<K, V, S, A>
fn extend<T: IntoIterator<Item = &'a (K, V)>>(self: &mut Self, iter: T)Inserts all new key-values from the iterator to existing
HashMap<K, V, S, A>. Replace values with existing keys with new values returned from the iterator. The keys and values must implementCopytrait.Examples
use HashMap; let mut map = new; map.insert; let arr = ; let some_iter = arr.iter; map.extend; // Replace values with existing keys with new values returned from the iterator. // So that the map.get(&1) doesn't return Some(&100). assert_eq!; let some_vec: = vec!; map.extend; let some_arr = ; map.extend; let mut vec: = map.into_iter.collect; // The `IntoIter` iterator produces items in arbitrary order, so the // items must be sorted to test them against a sorted array. vec.sort_unstable; assert_eq!;
impl<K, Q, V, S, A> Index for HashMap<K, V, S, A>
fn index(self: &Self, key: &Q) -> &VReturns a reference to the value corresponding to the supplied key.
Panics
Panics if the key is not present in the
HashMap.Examples
use HashMap; let map: = .into; assert_eq!; assert_eq!;
impl<K, V, S, A> Debug for HashMap<K, V, S, A>
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl<K, V, S, A> Default for HashMap<K, V, S, A>
fn default() -> SelfCreates an empty
HashMap<K, V, S, A>, with theDefaultvalue for the hasher and allocator.Examples
use HashMap; use RandomState; // You can specify all types of HashMap, including hasher and allocator. // Created map is empty and don't allocate memory let map: = Defaultdefault; assert_eq!; let map: = default; assert_eq!;
impl<K, V, S, A> Eq for HashMap<K, V, S, A>
impl<K, V, S, A> Extend for HashMap<K, V, S, A>
fn extend<T: IntoIterator<Item = (K, V)>>(self: &mut Self, iter: T)Inserts all new key-values from the iterator to existing
HashMap<K, V, S, A>. Replace values with existing keys with new values returned from the iterator.Examples
use HashMap; let mut map = new; map.insert; let some_iter = .into_iter; map.extend; // Replace values with existing keys with new values returned from the iterator. // So that the map.get(&1) doesn't return Some(&100). assert_eq!; let some_vec: = vec!; map.extend; let some_arr = ; map.extend; let old_map_len = map.len; // You can also extend from another HashMap let mut new_map = new; new_map.extend; assert_eq!; let mut vec: = new_map.into_iter.collect; // The `IntoIter` iterator produces items in arbitrary order, so the // items must be sorted to test them against a sorted array. vec.sort_unstable; assert_eq!;
impl<K, V, S, A> Freeze for HashMap<K, V, S, A>
impl<K, V, S, A> FromIterator for HashMap<K, V, S, A>
fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self
impl<K, V, S, A> PartialEq for HashMap<K, V, S, A>
fn eq(self: &Self, other: &Self) -> bool
impl<K, V, S, A> RefUnwindSafe for HashMap<K, V, S, A>
impl<K, V, S, A> Send for HashMap<K, V, S, A>
impl<K, V, S, A> Sync for HashMap<K, V, S, A>
impl<K, V, S, A> Unpin for HashMap<K, V, S, A>
impl<K, V, S, A> UnsafeUnpin for HashMap<K, V, S, A>
impl<K, V, S, A> UnwindSafe for HashMap<K, V, S, A>
impl<K, V, S, A: Allocator> IntoIterator for HashMap<K, V, S, A>
fn into_iter(self: Self) -> IntoIter<K, V, A>Creates a consuming iterator, that is, one that moves each key-value pair out of the map in arbitrary order. The map cannot be used after calling this.
Examples
use HashMap; let map: = .into; // Not possible with .iter() let mut vec: = map.into_iter.collect; // The `IntoIter` iterator produces items in arbitrary order, so // the items must be sorted to test them against a sorted array. vec.sort_unstable; assert_eq!;
impl<K: Clone, V: Clone, S: Clone, A: Allocator + Clone> Clone for HashMap<K, V, S, A>
fn clone(self: &Self) -> Selffn clone_from(self: &mut Self, source: &Self)
impl<Q, K> Equivalent for HashMap<K, V, S, A>
fn equivalent(self: &Self, key: &K) -> bool
impl<T> Any for HashMap<K, V, S, A>
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for HashMap<K, V, S, A>
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for HashMap<K, V, S, A>
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> CloneToUninit for HashMap<K, V, S, A>
unsafe fn clone_to_uninit(self: &Self, dest: *mut u8)
impl<T> From for HashMap<K, V, S, A>
fn from(t: T) -> TReturns the argument unchanged.
impl<T> ToOwned for HashMap<K, V, S, A>
fn to_owned(self: &Self) -> Tfn clone_into(self: &Self, target: &mut T)
impl<T, U> Into for HashMap<K, V, S, A>
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for HashMap<K, V, S, A>
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for HashMap<K, V, S, A>
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>