Collections and UTF-8 text.
Choose a collection by its operations and understand why text is not an array of characters.
The idea behind the syntax.
A Vec<T> owns a growable sequence. A HashMap<K,V> associates keys with values, while a HashSet<T> stores unique values. VecDeque<T> supports efficient operations at both ends. Their APIs differ because their costs and guarantees differ. A good data structure choice starts with what the program must do most often: preserve order, find by key, remove duplicates, or push at the front.
Rust strings store UTF-8 bytes. A visible character can use several bytes, and even one user-perceived symbol can consist of multiple Unicode scalar values. That is why indexing a String by a single integer is not supported: the integer would not identify an unambiguous character. Code can iterate bytes, scalar values with chars(), or grapheme clusters with a separate library when the user-facing notion of a character matters.
What Rust is checking.
Collections own their elements unless they are collections of references. Pushing a value into a vector may move it, and growing a vector may relocate its allocation. A reference into the vector cannot remain live across a mutation that could invalidate it. Iterating by reference reads elements without consuming the collection; into_iter transfers its elements to the iterator.
Hash maps have no meaningful display order, and key lookup returns an Option because a key may be absent. An entry API can express insert-or-update logic without duplicating lookup work. The examples compare these choices with concrete code. Notice where a program uses owned String values and where it can use borrowed &str views; the distinction affects allocation and API flexibility.
See the rule in context.
Each example isolates one part of the model. Follow the bindings, types, ownership transfers, and possible outcomes line by line.
String, str & Unicode
String owns a growable UTF-8 buffer; str is the dynamically sized text type usually used through &str. Use push for a char, push_str for a string slice, and format! when building a new formatted String. len counts bytes, chars iterates Unicode scalar values, and split_whitespace separates runs of whitespace. Case conversion can change the byte length. Be explicit about the text operation your product needs, especially for names, search, and cursor movement.
fn main() {
let mut title = String::from("Rust");
title.push_str(" café");
println!("{title}");
println!("bytes={}, scalars={}", title.len(), title.chars().count());
println!(
"{}",
title.split_whitespace().collect::<Vec<_>>().join(" / ")
);
}Rust café bytes=10, scalars=9 Rust / café
- The é needs two bytes in UTF-8.
- split_whitespace returns borrowed words.
- join constructs a new owned String.
The boundary: Do not split arbitrary user text at an assumed byte offset. Check boundaries or choose a character-aware operation.
Vec & dynamic collections
Vec<T> stores elements contiguously with a length and capacity. push adds an element, pop removes the final one, and get handles uncertain indexes. Capacity can exceed length and is not a promise that references remain valid forever. A growing vector may reallocate, which is why an active element reference can conflict with push. Borrow a slice when a function only needs to inspect elements, and consume into_iter when ownership of the elements should move into the loop.
fn main() {
let mut queue = vec!["plan", "build"];
queue.push("test");
println!("last={:?}", queue.pop());
for (index, task) in queue.iter().enumerate() {
println!("{index}: {task}");
}
}last=Some("test")
0: plan
1: build- push appends to the vector.
- pop returns Option because a vector may be empty.
- iter borrows each element and leaves the vector owned by main.
The boundary: Removing from the front of a Vec shifts later elements. Use VecDeque for a frequent FIFO workload.
HashMap & entry
HashMap<K, V> associates keys with values. insert takes ownership of owned keys and values; get borrows and returns Option<&V>. The entry API combines lookup with conditional insertion, which is useful for counters and caches. Iteration order is not a stable contract. Sort entries or use BTreeMap when deterministic key order is part of your output. Expected lookup is constant time under normal hashing assumptions, but hashing the key still costs work proportional to its representation.
use std::collections::HashMap;
fn main() {
let mut counts = HashMap::new();
for word in "build test build".split_whitespace() {
*counts.entry(word).or_insert(0_u32) += 1;
}
println!("build={}", counts["build"]);
println!("missing={:?}", counts.get("ship"));
}build=2 missing=None
- entry gives access to an existing or inserted counter.
- The keys borrow the static text in this example.
- get is appropriate when the key may not exist.
The boundary: Indexing a missing key panics. Use get when a missing entry is an expected possibility.
Sets, ordered maps & queues
HashSet keeps unique values and supports membership operations. BTreeMap and BTreeSet maintain sorted key order and logarithmic tree operations. VecDeque provides efficient insertion and removal at both ends, making it a natural FIFO queue. A collection choice is an operational contract: think about lookup, insertion, ordering, and how you will iterate. Avoid introducing a hash table just because it is familiar when a short vector or sorted map expresses the work more clearly.
use std::collections::{BTreeSet, VecDeque};
fn main() {
let names: BTreeSet<_> = ["Rust", "Python", "Rust"].into_iter().collect();
let mut queue = VecDeque::from(["build", "test"]);
queue.push_back("ship");
println!("{names:?}");
println!("next={:?}", queue.pop_front());
}{"Python", "Rust"}
next=Some("build")- The set removes duplicates.
- BTreeSet iteration is sorted.
- pop_front implements the next FIFO operation.
The boundary: Sorted order and insertion order are different contracts. Choose explicitly.
Keep this model.
Choose collections from required operations, and choose the unit of text deliberately: byte, scalar value, or user-perceived grapheme.