Start with the idea
Choosing a collection is part of the model, not an afterthought: order, uniqueness, and key access all change what your code can promise. Each of these owns its data, so passing one around follows exactly the same ownership rules as any other value.
Choose a collection by the operations the program promises. Vec<T> preserves an ordered sequence and supports indexed access; appending is a natural operation. HashMap<K, V> associates keys with values and is useful for lookup or counting, but its iteration order is not a stable presentation order. A String owns UTF-8 text rather than an arbitrary sequence of characters. Naming the data structure early keeps later code from relying on an accidental property, such as hash iteration looking sorted in one run.
The entry API handles the common "insert if missing, then update" operation in one lookup. counts.entry(word).or_insert(0) returns a mutable reference to the existing count or to a newly inserted zero.
Keep learning, for free
The rest of this lesson is waiting for you.
Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.
No payment details. Your account opens the complete Academy.