Collecting Into Different Types
Medium
+3 pts
🎯 In Python, converting between collection types is effortless:
numbers = [3, 1, 2, 1, 3]
unique = set(numbers) # {1, 2, 3}
sorted_list = sorted(unique) # [1, 2, 3]
pairs = [("a", 1), ("b", 2)]
lookup = dict(pairs) # {"a": 1, "b": 2}
from collections import Counter
Counter(["red", "blue", "red"]) # {'red': 2, 'blue': 1}
You call set(), dict(), list(), sorted() — the constructor does the work. In Rust, one method does all of this: .collect(). What it collects into depends on the type annotation.
.collect() — one method, many targets
.collect() consumes an iterator and builds a collection. The type annotation tells Rust which collection to create:
let v: Vec<i32> = (1..=5).collect(); // [1, 2, 3, 4, 5]
use std::collections::HashSet;
let set: HashSet<i32> = (1..=5).collect(); // {1, 2, 3, 4, 5}
let s: String = vec!['h', 'i'].into_iter().collect(); // "hi"
Same iterator, same .collect() call — different results. This is …
Login to see the full exercise.