Skip to content

Collections

JavaScript’s Array, Object, and Map cover most collection needs. Rust has direct equivalents with one key difference: collections are typed and fixed-element — a Vec<i32> holds only i32 values and the compiler enforces it.

Vec<T> is Rust’s heap-allocated growable array, equivalent to a JS array (when all elements share a type). Create one with the vec! macro or Vec::new().

Fixed-size arrays [T; N] live on the stack. Tuples (T1, T2, ...) hold heterogeneous values — similar to a TypeScript tuple type.

HashMap<K, V> is Rust’s equivalent of a JS Map or a TS Record<string, V>. It lives in std::collections.

Rust iterators are lazy and composable — filter, map, collect work like JS array methods but are evaluated only when consumed.

TypeScript
// Array
const numbers = [1, 2, 3, 4, 5];
const odds = numbers.filter(x => x % 2 !== 0);
console.log(odds); // [1, 3, 5]
// Map
const scores = new Map<string, number>();
scores.set("Alice", 95);
scores.set("Bob", 87);
console.log(scores.get("Alice")); // 95
// Tuple (TypeScript)
const pair: [string, number] = ["Alice", 95];
Rust
use std::collections::HashMap;
fn main() {
// Vec
let numbers = vec![1, 2, 3, 4, 5];
let odds: Vec<i32> = numbers.iter()
.filter(|&&x| x % 2 != 0)
.copied()
.collect();
println!("{:?}", odds); // [1, 3, 5]
// HashMap
let mut scores: HashMap<&str, i32> = HashMap::new();
scores.insert("Alice", 95);
scores.insert("Bob", 87);
if let Some(s) = scores.get("Alice") {
println!("{s}"); // 95
}
// Tuple
let pair: (&str, i32) = ("Alice", 95);
println!("{} scored {}", pair.0, pair.1);
}
fn main() {
let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let odds: Vec<i32> = numbers.iter().filter(|&&x| x % 2 != 0).copied().collect();
println!("Odd numbers: {:?}", odds);
let mut scores = std::collections::HashMap::new();
scores.insert("Alice", 95);
scores.insert("Bob", 87);
if let Some(s) = scores.get("Alice") {
println!("Alice scored {s}");
}
}
What is the Rust equivalent of a JavaScript growable array?
What does `.collect()` do at the end of a Rust iterator chain?
How do you access the second element of a Rust tuple `t`?