Collections
Vec<T> is a growable list, Map<K, V> a hash map and Set<T> a hash set.
All three have literals.
let mut scores = Map { "ada": 3, "linus": 5 }scores.insert("grace", 7)let mut seen = Set { "ada" }seen.insert("grace")let mut names: Vec<Str> = []for (name, score) in &scores { if *score > 4 { names.push(name.clone()) }}names.sort()print(names.join(", "))print(f"{scores.len()} {seen.contains(&"linus")} {scores.get("ada").unwrap()}")grace, linus3 false 3A map literal with the same key twice is a compile error.
Working with Vec
Section titled “Working with Vec”let mut v = [5, 3, 8, 3, 1]v.sort()v.dedup()print(f"{v.len()} {v.binary_search(5).unwrap()}")v.insert_sorted(4)print(v.map(fn(n) => n.to_str()).join(" "))for pair in v.windows(2) { print(f"{pair[1] - pair[0]}")}let evens = v.filter(fn(n) => *n % 2 == 0)print(f"{evens.len()} {v.any(fn(n) => *n > 7)}")4 21 3 4 5 821132 trueIterators
Section titled “Iterators”iter() gives an iterator; map, filter, take, skip, enumerate,
zip and chain build new ones, and collect() gathers the result.
Nothing runs until the iterator is used.
let words = ["one", "three", "five", "seven"]let long = words.iter().filter(fn(w) => w.len() > 3).map(fn(w) => w.to_upper()).collect()print(long.join(" "))for (i, w) in words.iter().enumerate().skip(2) { print(f"{i} {w}")}THREE FIVE SEVEN2 five3 sevenThe collections module adds Queue (first in, first out) and Heap
(always gives the smallest item first).