Collections
Collections in JavaScript vs Rust
Section titled “Collections in JavaScript vs Rust”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 — the growable array
Section titled “Vec — the growable array”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().
Arrays and tuples
Section titled “Arrays and tuples”Fixed-size arrays [T; N] live on the stack. Tuples (T1, T2, ...) hold heterogeneous values — similar to a TypeScript tuple type.
HashMap — key/value store
Section titled “HashMap — key/value store”HashMap<K, V> is Rust’s equivalent of a JS Map or a TS Record<string, V>. It lives in std::collections.
Iteration
Section titled “Iteration”Rust iterators are lazy and composable — filter, map, collect work like JS array methods but are evaluated only when consumed.
// Arrayconst numbers = [1, 2, 3, 4, 5];const odds = numbers.filter(x => x % 2 !== 0);console.log(odds); // [1, 3, 5]
// Mapconst 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];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);}Try it
Section titled “Try it”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}"); }}Compiling…