Collections
Arrays and tuples from the Variables and Types topic have a size known at compile time. A real program works with data whose amount only becomes clear while it runs: the lines of a file, records from a database, the words of a text. For that data the standard library provides collections — types that keep their elements on the heap and grow as needed. Three of them appear in almost every program: the vector Vec<T>, the string String and the hash table HashMap<K, V>.
Collections obey ownership: a collection owns its elements, an insertion moves the value inside, and dropping the collection drops the elements too. The main interview questions follow from how collections are built. Why does push not compile while a reference to an element is alive? Because a growing vector moves its elements into a new buffer. Why is "привет".len() equal to 12? Because a String stores UTF-8 bytes, not characters — and for the same reason s[0] does not compile. Why can you not print a HashMap traversal in a test? Because its order is unspecified. This topic walks collections layer by layer — from the vector to choosing between BTreeMap, VecDeque and BinaryHeap.
Topic map
- Vec Basics —
Vec::new,vec![],pushandpop; an index past the end panics,getreturns anOption; iterating with&v,&mut vandv; whypushdoes not compile next to&v[0](E0502). - Length and Capacity —
lenversuscapacity, growth 0 → 4 → 8 → 16 and the amortized O(1) ofpush;with_capacity,reserve,shrink_to_fitand what reallocation does to the buffer. - The String Type — UTF-8 bytes in a growable buffer versus the borrowed
&str;lenin bytes, nos[0](E0277),charsandbytes; what+takes; grapheme clusters. - HashMap Basics —
insert,get,remove; the map owns its keys and values; iteration order is unspecified; SipHash and consistentEqandHashon the key. - The Entry API — one lookup instead of "check, then insert";
or_insert,or_insert_with,or_default,and_modifyand the word-count idiom. - Other Collections —
HashSet, the orderedBTreeMapandBTreeSet, the double-ended queueVecDequeandBinaryHeap; when to use which and what the operations cost.
Common mistakes and traps
| Mistake | Consequence |
|---|---|
Holding &v[0] and calling v.push(…) | error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable: push may move the elements into a new buffer |
Accessing v[i] with an unchecked index | The panic index out of bounds: the len is 3 but the index is 5; the safe way is v.get(i) |
Treating s.len() as the number of characters | It is bytes: "привет".len() is 12; s.chars().count() counts characters |
Writing s[0] to get the first character | error[E0277]: the type `str` cannot be indexed by `{integer}` ; you need s.chars().next() |
Using a after let c = a + &b; | error[E0382]: borrow of moved value: `a` : + takes the left string |
Printing a HashMap traversal or checking its order in a test | The order is unspecified and changes from run to run |
Building a queue from a Vec with remove(0) | Every call shifts all the elements — O(n); you need a VecDeque |
Why it matters in interviews
At the junior level, collections test whether a candidate sees the memory layout behind a convenient API: a buffer that relocates as it grows, bytes instead of characters, a hash table with no order. Live coding almost always needs a HashMap — to count frequencies or to find a pair with a given sum in one pass instead of two nested loops.
What interviewers usually check:
- How a vector's length differs from its capacity, what happens on
pushinto a full vector, and whywith_capacityexists. - Why
pushdoes not compile while a reference to an element of the vector is alive. - How
Stringdiffers from&str, and which of them to accept as a function parameter. - Why a string cannot be indexed with
s[0], and how bytes differ fromchars and grapheme clusters. - How to count words with
entry, and why the iteration order of aHashMapis unspecified. - Which collection to pick for a queue, for ordered keys, and for "take out the largest".