HashMap
class HashMap<K, V> Import
Source: use collections::map::{HashMap}; src/collections/map.hy A hash map from keys of type K to values of type V.
Keys need Eq and Hash (the primitive types have both; #[derive(Eq, Hash)]
adds them to your own types). Inserting an existing key replaces its value.
Iteration (for e in m, m.keys(), m.values()) visits entries in
insertion order, skipping removed ones.
get takes a fallback instead of returning an Option; use contains first
when the fallback could be a real value.
Fields#
| Field | Type | Description |
|---|---|---|
keys | Vec<K> | Key slots, including removed ones (see live). Prefer keys(). |
vals | Vec<V> | Value slots parallel to keys. Prefer values(). |
live | Vec<int> | 1 where the slot holds an entry, 0 where it was removed. |
Associated functions#
| Name | Description |
|---|---|
with_capacity | Creates an empty map with room for about cap buckets before it grows. |
new | Creates an empty map. |
Methods#
| Name | Description |
|---|---|
size | Returns the number of entries. |
is_empty | Returns true when the map has no entries. |
capacity | Returns the number of buckets. |
clear | Removes every entry, keeping the bucket count. |
keys | Returns the keys, in insertion order. |
values | Returns the values, in the insertion order of their keys. |
iter | Returns an iterator over the entries, in insertion order. |
insert | Stores v under k, replacing any value already there. |
contains | Returns true when the map has an entry for k. |
get_or | Returns the value stored under k, or fallback when there is none. |
get | Returns the value stored under k, or None when there is none. |
remove | Removes the entry for k. |
Trait implementations#
IntoIteratorforHashMap<K, V>
Invariants#
Checked according to --contracts (see Contracts).
invariant self.len >= 0 && self.len <= self.keys.len()
invariant self.cap >= 8 && self.heads.len() == self.cap
invariant self.vals.len() == self.keys.len() && self.next.len() == self.keys.len()
invariant self.live.len() == self.keys.len()
Examples#
use collections::map::{HashMap};
use tests::assert;
let ages: HashMap<string, int> = HashMap::new();
ages.insert("ada", 36);
ages.insert("alan", 41);
ages.insert("ada", 37);
assert!(ages.size() == 2);
assert!(ages.get_or("ada", 0) == 37);
assert!(ages.get_or("grace", -1) == -1);
let total = 0;
for e in ages {
total = total + e.value;
}
assert!(total == 78);
See also#
EqHashMap::getOptionHashMap::containsHashMap::keysHashMap::valuesEntry: One key-value pair, asHashMapiteration yields it.HashMapIter: An iterator over the entries of aHashMap, fromHashMap::iter.