Module 5 • Lesson 29

Collecting and Consuming

📚 8 min read💻 Free Course🦀 nixus.pro

Collecting and Consuming Iterators

use std::collections::{HashMap, HashSet, BTreeMap};

fn main() {
    let numbers = vec![3, 1, 4, 1, 5, 9, 2, 6, 5, 3];

    // Collect into different types
    let set: HashSet = numbers.iter().cloned().collect();
    let sorted: BTreeMap = numbers.iter().map(|&x| (x, ())).collect();
    println!("{:?}", set);

    // String collection
    let words = vec!["hello", "world", "rust"];
    let joined: String = words.join(", ");
    let concat: String = words.iter().cloned().collect();
    println!("{}", joined);  // "hello, world, rust"
    println!("{}", concat);  // "helloworldrust"

    // Collecting Results: Vec> -> Result,E>
    let inputs = vec!["1", "2", "3", "4"];
    let parsed: Result, _> = inputs.iter()
        .map(|s| s.parse::())
        .collect();
    println!("{:?}", parsed); // Ok([1, 2, 3, 4])

    let bad = vec!["1", "oops", "3"];
    let parsed2: Result, _> = bad.iter()
        .map(|s| s.parse::())
        .collect();
    println!("{}", parsed2.is_err()); // true

    // Group by (manual)
    let data = vec![("a", 1), ("b", 2), ("a", 3), ("b", 4)];
    let mut grouped: HashMap<&str, Vec> = HashMap::new();
    for (k, v) in data { grouped.entry(k).or_insert_with(Vec::new).push(v); }
    println!("{:?}", grouped);
}

🎯 Practice

  1. Collect a Vec<&str> of "key=value" strings into a HashMap<&str, &str>
  2. Use the Result-collecting pattern to validate a list of email addresses
  3. Group a Vec<(String, u32)> by first letter of the String into a HashMap

🎉 Key Takeaways