Rust Learning Path — Chapter 11. This chapter introduces the collection types you will use constantly in real Rust applications: Vec , HashMap , and HashSet .
Why collections matter
Arrays have a fixed size. Collections can grow and shrink at runtime and are stored on the heap. Rust's standard collection library provides efficient general-purpose data structures; Vec and HashMap are especially common.
1. Vec — growable list
fn main() { let mut ports = vec![80, 443]; ports.push(8080); ports.push(8443); println!("{:?}", ports); println!("first = {}", ports[0]); }A vector stores values of one type in order. Use get() when an index may be invalid:
match ports.get(10) { Some(port) => println!("{port}"), None => println!("No port at that index"), }Iterating and mutating a vector
let mut scores = vec![10, 20, 30]; for score in &scores { println!("{score}"); } for score in &mut scores { *score += 5; }2. HashMap — key/value storage
use std::collections::HashMap; fn main() { let mut servers = HashMap::new(); servers.insert("api", "10.0.0.10"); servers.insert("db", "10.0.0.20"); if let Some(ip) = servers.get("api") { println!("API server: {ip}"); } }Update only when missing with entry()
let mut counts = HashMap::new(); counts.entry("rust").or_insert(0); *counts.entry("rust").or_insert(0) += 1;3. HashSet — unique values
use std::collections::HashSet; fn main() { let mut roles = HashSet::new(); roles.insert("admin"); roles.insert("editor"); roles.insert("admin"); println!("{}", roles.len()); // 2 println!("{}", roles.contains("admin")); }A set is useful for unique IDs, permissions, tags, deduplication and membership tests.
Vec vs HashMap vs HashSet
| Collection | Use when | Example |
| Vec | You need an ordered growable list | API endpoints |
| HashMap | You need lookup by key | User ID → profile |
| HashSet | You need unique values | Permissions |
Ownership with collections
Collections own values inserted into them unless you deliberately store references. This matters with heap-owning values such as String .
use std::collections::HashMap; let key = String::from("service"); let value = String::from("payments"); let mut map = HashMap::new(); map.insert(key, value); // key and value have moved into mapMini lab: inventory counter
use std::collections::{HashMap, HashSet}; fn main() { let items = vec!["api", "db", "api", "cache", "db", "api"]; let mut counts = HashMap::new(); let mut unique = HashSet::new(); for item in items { unique.insert(item); *counts.entry(item).or_insert(0) += 1; } println!("Counts: {counts:?}"); println!("Unique: {unique:?}"); }Common mistakes
- Indexing a vector without checking when the index is user-controlled.
- Forgetting that inserting owned values can move them.
- Trying to mutate a collection while an incompatible borrow is still active.
- Using a map when a set is enough.
Practice checklist
cargo fmt --check cargo clippy cargo test cargo runNext: Chapter 12 — Error Handling with Result , panic! , and the ? operator.
Join the discussion
0 CommentsAsk questions, add context, or share what worked.
More from Melochip Editorial
Learn what Playwright testing is, why modern QA teams use it, how testers can get started, and the major types...
7 min read · Sep 19, 2026
Learn how Kubernetes Deployments and ReplicaSets work with practical YAML, scaling, self-healing, rolling upda...
7 min read · Sep 17, 2026
Learn Kubernetes security best practices with RBAC, Secrets, ServiceAccounts, Pod securityContext, NetworkPoli...
6 min read · Sep 17, 2026Related articles
Learn Docker environment variables and secrets, including docker run -e, env files, Compose environment, secre...
2 min read · Sep 17, 2026
Learn how Kubernetes Deployments and ReplicaSets work with practical YAML, scaling, self-healing, rolling upda...
7 min read · Sep 17, 2026
Learn Kubernetes monitoring and logs with kubectl logs, events, metrics-server, top commands, Prometheus, Graf...
5 min read · Sep 17, 2026
Learn Kubernetes Ingress with controllers, IngressClass, host and path routing, TLS, DNS, annotations, redirec...
8 min read · Sep 17, 2026Stay in the loop. Get new Melochip articles
Receive Melochip article updates when new articles are available. Explicit opt-in only.
No comments yet. Start the discussion.