Struct std::collections::HashMap
[−]
[src]
pub struct HashMap<K, V, S = RandomState> { // some fields omitted }1.0.0
A hash map implementation which uses linear probing with Robin Hood bucket stealing.
The hashes are all keyed by the thread-local random number generator on creation by default. This means that the ordering of the keys is randomized, but makes the tables more resistant to denial-of-service attacks (Hash DoS). This behavior can be overridden with one of the constructors.
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.
Relevant papers/articles:
- Pedro Celis. "Robin Hood Hashing"
- Emmanuel Goossaert. "Robin Hood hashing"
- Emmanuel Goossaert. "Robin Hood hashing: backward shift deletion"
Examples
fn main() { use std::collections::HashMap; // type inference lets us omit an explicit type signature (which // would be `HashMap<&str, &str>` in this example). let mut book_reviews = HashMap::new(); // review some books. book_reviews.insert("Adventures of Huckleberry Finn", "My favorite book."); book_reviews.insert("Grimms' Fairy Tales", "Masterpiece."); book_reviews.insert("Pride and Prejudice", "Very enjoyable."); book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot."); // check for a specific one. if !book_reviews.contains_key("Les Misérables") { println!("We've got {} reviews, but Les Misérables ain't one.", book_reviews.len()); } // oops, this review has a lot of spelling mistakes, let's delete it. book_reviews.remove("The Adventures of Sherlock Holmes"); // look up the values associated with some keys. let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"]; for book in &to_find { match book_reviews.get(book) { Some(review) => println!("{}: {}", book, review), None => println!("{} is unreviewed.", book) } } // iterate over everything. for (book, review) in &book_reviews { println!("{}: \"{}\"", book, review); } }use std::collections::HashMap; // type inference lets us omit an explicit type signature (which // would be `HashMap<&str, &str>` in this example). let mut book_reviews = HashMap::new(); // review some books. book_reviews.insert("Adventures of Huckleberry Finn", "My favorite book."); book_reviews.insert("Grimms' Fairy Tales", "Masterpiece."); book_reviews.insert("Pride and Prejudice", "Very enjoyable."); book_reviews.insert("The Adventures of Sherlock Holmes", "Eye lyked it alot."); // check for a specific one. if !book_reviews.contains_key("Les Misérables") { println!("We've got {} reviews, but Les Misérables ain't one.", book_reviews.len()); } // oops, this review has a lot of spelling mistakes, let's delete it. book_reviews.remove("The Adventures of Sherlock Holmes"); // look up the values associated with some keys. let to_find = ["Pride and Prejudice", "Alice's Adventure in Wonderland"]; for book in &to_find { match book_reviews.get(book) { Some(review) => println!("{}: {}", book, review), None => println!("{} is unreviewed.", book) } } // iterate over everything. for (book, review) in &book_reviews { println!("{}: \"{}\"", book, review); }
HashMap
also implements an Entry API
, which allows
for more complex methods of getting, setting, updating and removing keys and
their values:
use std::collections::HashMap; // type inference lets us omit an explicit type signature (which // would be `HashMap<&str, u8>` in this example). let mut player_stats = HashMap::new(); fn random_stat_buff() -> u8 { // could actually return some random value here - let's just return // some fixed value for now 42 } // insert a key only if it doesn't already exist player_stats.entry("health").or_insert(100); // insert a key using a function that provides a new value only if it // doesn't already exist player_stats.entry("defence").or_insert_with(random_stat_buff); // update a key, guarding against the key possibly not being set let stat = player_stats.entry("attack").or_insert(100); *stat += random_stat_buff();
The easiest way to use HashMap
with a custom type as key is to derive Eq
and Hash
.
We must also derive PartialEq
.
use std::collections::HashMap; #[derive(Hash, Eq, PartialEq, Debug)] struct Viking { name: String, country: String, } impl Viking { /// Create a new Viking. fn new(name: &str, country: &str) -> Viking { Viking { name: name.to_string(), country: country.to_string() } } } // Use a HashMap to store the vikings' health points. let mut vikings = HashMap::new(); vikings.insert(Viking::new("Einar", "Norway"), 25); vikings.insert(Viking::new("Olaf", "Denmark"), 24); vikings.insert(Viking::new("Harald", "Iceland"), 12); // Use derived implementation to print the status of the vikings. for (viking, health) in &vikings { println!("{:?} has {} hp", viking, health); }
Methods
impl<K: Hash + Eq, V> HashMap<K, V, RandomState>
fn new() -> HashMap<K, V, RandomState>
Creates an empty HashMap.
Examples
fn main() { use std::collections::HashMap; let mut map: HashMap<&str, isize> = HashMap::new(); }use std::collections::HashMap; let mut map: HashMap<&str, isize> = HashMap::new();
fn with_capacity(capacity: usize) -> HashMap<K, V, RandomState>
Creates an empty hash map with the given initial capacity.
Examples
fn main() { use std::collections::HashMap; let mut map: HashMap<&str, isize> = HashMap::with_capacity(10); }use std::collections::HashMap; let mut map: HashMap<&str, isize> = HashMap::with_capacity(10);
impl<K, V, S> HashMap<K, V, S> where K: Eq + Hash, S: BuildHasher
fn with_hasher(hash_builder: S) -> HashMap<K, V, S>
1.7.0
Creates an empty hashmap which will use the given hash builder to hash keys.
The created map has the default initial capacity.
Warning: hash_builder
is normally randomly generated, and
is designed to allow HashMaps to be resistant to attacks that
cause many collisions and very poor performance. Setting it
manually using this function can expose a DoS attack vector.
Examples
fn main() { use std::collections::HashMap; use std::collections::hash_map::RandomState; let s = RandomState::new(); let mut map = HashMap::with_hasher(s); map.insert(1, 2); }use std::collections::HashMap; use std::collections::hash_map::RandomState; let s = RandomState::new(); let mut map = HashMap::with_hasher(s); map.insert(1, 2);
fn with_capacity_and_hasher(capacity: usize, hash_builder: S) -> HashMap<K, V, S>
1.7.0
Creates an empty HashMap with space for at least capacity
elements, using hasher
to hash the keys.
Warning: hasher
is normally randomly generated, and
is designed to allow HashMaps to be resistant to attacks that
cause many collisions and very poor performance. Setting it
manually using this function can expose a DoS attack vector.
Examples
fn main() { use std::collections::HashMap; use std::collections::hash_map::RandomState; let s = RandomState::new(); let mut map = HashMap::with_capacity_and_hasher(10, s); map.insert(1, 2); }use std::collections::HashMap; use std::collections::hash_map::RandomState; let s = RandomState::new(); let mut map = HashMap::with_capacity_and_hasher(10, s); map.insert(1, 2);
fn hasher(&self) -> &S
1.9.0
Returns a reference to the map's hasher.
fn capacity(&self) -> usize
Returns 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
fn main() { use std::collections::HashMap; let map: HashMap<isize, isize> = HashMap::with_capacity(100); assert!(map.capacity() >= 100); }use std::collections::HashMap; let map: HashMap<isize, isize> = HashMap::with_capacity(100); assert!(map.capacity() >= 100);
fn reserve(&mut self, additional: usize)
Reserves capacity for at least additional
more elements to be inserted
in the HashMap
. The collection may reserve more space to avoid
frequent reallocations.
Panics
Panics if the new allocation size overflows usize
.
Examples
fn main() { use std::collections::HashMap; let mut map: HashMap<&str, isize> = HashMap::new(); map.reserve(10); }use std::collections::HashMap; let mut map: HashMap<&str, isize> = HashMap::new(); map.reserve(10);
fn shrink_to_fit(&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
fn main() { use std::collections::HashMap; let mut map: HashMap<isize, isize> = HashMap::with_capacity(100); map.insert(1, 2); map.insert(3, 4); assert!(map.capacity() >= 100); map.shrink_to_fit(); assert!(map.capacity() >= 2); }use std::collections::HashMap; let mut map: HashMap<isize, isize> = HashMap::with_capacity(100); map.insert(1, 2); map.insert(3, 4); assert!(map.capacity() >= 100); map.shrink_to_fit(); assert!(map.capacity() >= 2);
fn keys(&self) -> Keys<K, V>
An iterator visiting all keys in arbitrary order.
Iterator element type is &'a K
.
Examples
fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); for key in map.keys() { println!("{}", key); } }use std::collections::HashMap; let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); for key in map.keys() { println!("{}", key); }
fn values(&self) -> Values<K, V>
An iterator visiting all values in arbitrary order.
Iterator element type is &'a V
.
Examples
fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); for val in map.values() { println!("{}", val); } }use std::collections::HashMap; let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); for val in map.values() { println!("{}", val); }
fn values_mut<'a>(&'a mut self) -> ValuesMut<K, V>
An iterator visiting all values mutably in arbitrary order.
Iterator element type is &'a mut V
.
Examples
#![feature(map_values_mut)] fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); for val in map.values_mut() { *val = *val + 10; } for val in map.values() { print!("{}", val); } }use std::collections::HashMap; let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); for val in map.values_mut() { *val = *val + 10; } for val in map.values() { print!("{}", val); }
fn iter(&self) -> Iter<K, V>
An iterator visiting all key-value pairs in arbitrary order.
Iterator element type is (&'a K, &'a V)
.
Examples
fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); for (key, val) in map.iter() { println!("key: {} val: {}", key, val); } }use std::collections::HashMap; let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); for (key, val) in map.iter() { println!("key: {} val: {}", key, val); }
fn iter_mut(&mut self) -> IterMut<K, V>
An iterator visiting all key-value pairs in arbitrary order,
with mutable references to the values.
Iterator element type is (&'a K, &'a mut V)
.
Examples
fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); // Update all values for (_, val) in map.iter_mut() { *val *= 2; } for (key, val) in &map { println!("key: {} val: {}", key, val); } }use std::collections::HashMap; let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); // Update all values for (_, val) in map.iter_mut() { *val *= 2; } for (key, val) in &map { println!("key: {} val: {}", key, val); }
fn entry(&mut self, key: K) -> Entry<K, V>
Gets the given key's corresponding entry in the map for in-place manipulation.
Examples
fn main() { use std::collections::HashMap; let mut letters = HashMap::new(); for ch in "a short treatise on fungi".chars() { let counter = letters.entry(ch).or_insert(0); *counter += 1; } assert_eq!(letters[&'s'], 2); assert_eq!(letters[&'t'], 3); assert_eq!(letters[&'u'], 1); assert_eq!(letters.get(&'y'), None); }use std::collections::HashMap; let mut letters = HashMap::new(); for ch in "a short treatise on fungi".chars() { let counter = letters.entry(ch).or_insert(0); *counter += 1; } assert_eq!(letters[&'s'], 2); assert_eq!(letters[&'t'], 3); assert_eq!(letters[&'u'], 1); assert_eq!(letters.get(&'y'), None);
fn len(&self) -> usize
Returns the number of elements in the map.
Examples
fn main() { use std::collections::HashMap; let mut a = HashMap::new(); assert_eq!(a.len(), 0); a.insert(1, "a"); assert_eq!(a.len(), 1); }use std::collections::HashMap; let mut a = HashMap::new(); assert_eq!(a.len(), 0); a.insert(1, "a"); assert_eq!(a.len(), 1);
fn is_empty(&self) -> bool
Returns true if the map contains no elements.
Examples
fn main() { use std::collections::HashMap; let mut a = HashMap::new(); assert!(a.is_empty()); a.insert(1, "a"); assert!(!a.is_empty()); }use std::collections::HashMap; let mut a = HashMap::new(); assert!(a.is_empty()); a.insert(1, "a"); assert!(!a.is_empty());
fn drain(&mut self) -> Drain<K, V>
1.6.0
Clears the map, returning all key-value pairs as an iterator. Keeps the allocated memory for reuse.
Examples
fn main() { use std::collections::HashMap; let mut a = HashMap::new(); a.insert(1, "a"); a.insert(2, "b"); for (k, v) in a.drain().take(1) { assert!(k == 1 || k == 2); assert!(v == "a" || v == "b"); } assert!(a.is_empty()); }use std::collections::HashMap; let mut a = HashMap::new(); a.insert(1, "a"); a.insert(2, "b"); for (k, v) in a.drain().take(1) { assert!(k == 1 || k == 2); assert!(v == "a" || v == "b"); } assert!(a.is_empty());
fn clear(&mut self)
Clears the map, removing all key-value pairs. Keeps the allocated memory for reuse.
Examples
fn main() { use std::collections::HashMap; let mut a = HashMap::new(); a.insert(1, "a"); a.clear(); assert!(a.is_empty()); }use std::collections::HashMap; let mut a = HashMap::new(); a.insert(1, "a"); a.clear(); assert!(a.is_empty());
fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V> where K: Borrow<Q>, Q: Hash + Eq
Returns a reference to the value corresponding to the key.
The key may be any borrowed form of the map's key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
Examples
fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None); }use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.get(&1), Some(&"a")); assert_eq!(map.get(&2), None);
fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool where K: Borrow<Q>, Q: Hash + Eq
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
Hash
and Eq
on the borrowed form must match those for
the key type.
Examples
fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.contains_key(&1), true); assert_eq!(map.contains_key(&2), false); }use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.contains_key(&1), true); assert_eq!(map.contains_key(&2), false);
fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V> where K: Borrow<Q>, Q: Hash + Eq
Returns a mutable reference to the value corresponding to the key.
The key may be any borrowed form of the map's key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
Examples
fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); if let Some(x) = map.get_mut(&1) { *x = "b"; } assert_eq!(map[&1], "b"); }use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); if let Some(x) = map.get_mut(&1) { *x = "b"; } assert_eq!(map[&1], "b");
fn insert(&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, None
is 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 the module-level
documentation for more.
Examples
fn main() { use std::collections::HashMap; let mut map = HashMap::new(); assert_eq!(map.insert(37, "a"), None); assert_eq!(map.is_empty(), false); map.insert(37, "b"); assert_eq!(map.insert(37, "c"), Some("b")); assert_eq!(map[&37], "c"); }use std::collections::HashMap; let mut map = HashMap::new(); assert_eq!(map.insert(37, "a"), None); assert_eq!(map.is_empty(), false); map.insert(37, "b"); assert_eq!(map.insert(37, "c"), Some("b")); assert_eq!(map[&37], "c");
fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V> where K: Borrow<Q>, Q: Hash + Eq
Removes a key from the map, returning the value at the key if the key was previously in the map.
The key may be any borrowed form of the map's key type, but
Hash
and Eq
on the borrowed form must match those for
the key type.
Examples
fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.remove(&1), Some("a")); assert_eq!(map.remove(&1), None); }use std::collections::HashMap; let mut map = HashMap::new(); map.insert(1, "a"); assert_eq!(map.remove(&1), Some("a")); assert_eq!(map.remove(&1), None);
Trait Implementations
impl<K, V, S> PartialEq for HashMap<K, V, S> where K: Eq + Hash, V: PartialEq, S: BuildHasher
impl<K, V, S> Eq for HashMap<K, V, S> where K: Eq + Hash, V: Eq, S: BuildHasher
impl<K, V, S> Debug for HashMap<K, V, S> where K: Eq + Hash + Debug, V: Debug, S: BuildHasher
impl<K, V, S> Default for HashMap<K, V, S> where K: Eq + Hash, S: BuildHasher + Default
impl<'a, K, Q: ?Sized, V, S> Index<&'a Q> for HashMap<K, V, S> where K: Eq + Hash + Borrow<Q>, Q: Eq + Hash, S: BuildHasher
impl<'a, K, V, S> IntoIterator for &'a HashMap<K, V, S> where K: Eq + Hash, S: BuildHasher
impl<'a, K, V, S> IntoIterator for &'a mut HashMap<K, V, S> where K: Eq + Hash, S: BuildHasher
type Item = (&'a K, &'a mut V)
type IntoIter = IterMut<'a, K, V>
fn into_iter(self) -> IterMut<'a, K, V>
impl<K, V, S> IntoIterator for HashMap<K, V, S> where K: Eq + Hash, S: BuildHasher
type Item = (K, V)
type IntoIter = IntoIter<K, V>
fn into_iter(self) -> IntoIter<K, V>
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
fn main() { use std::collections::HashMap; let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); // Not possible with .iter() let vec: Vec<(&str, isize)> = map.into_iter().collect(); }use std::collections::HashMap; let mut map = HashMap::new(); map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); // Not possible with .iter() let vec: Vec<(&str, isize)> = map.into_iter().collect();