Collections - using hashmaps and hashsets
Often, you need to collect a large number of data items of a given type in one data structure. Until now, we have only worked with the Vec
datatype to do this, but the std::collections
module contains other implementations of sequences (such as LinkedList
), maps (such as HashMap
), and sets (such as HashSet
). In most cases, you will only need Vec
and HashMap
; let's examine how to work with the latter.
A HashMap <K,V>
is used when you want to store pairs consisting of a key of type K
and a value of type V
, both of generic type. K
can be a Boolean, an integer, a string, or any other type that implements the Eq
and Hash
traits. A HashMap
enables you to very quickly look up the value attached to a certain key using a hashing algorithm, and also because the data is cached. However, the keys of a HashMap
are not sorted; if you need that, use a BTreeMap
. HashMap
is allocated on the heap, so it is dynamically resizable, just like a Vec
.
Let's store monster...