Collect Iterators Into Maps And Sets

Choose the destination type and collect fills it: pairs become HashMap or ordered BTreeMap entries, and duplicate values collapse inside HashSet.

RustData Integrity

Code

rustsnippet
24 lines
use std::collections::{BTreeMap, HashMap, HashSet};

fn main() {
    let rows = vec![("eu", 120), ("us", 80), ("eu", 45)];

    // 收集目标由类型标注决定:成对数据直接进 map(后写覆盖先写)
    let latest: HashMap<&str, i32> = rows.clone().into_iter().collect();
    println!("eu now: {:?}", latest["eu"]);

    // BTreeMap 让键有序,输出稳定可对比
    let ordered: BTreeMap<&str, i32> = rows.clone().into_iter().collect();
    println!("{ordered:?}");

    // HashSet 收集时自动去重
    let regions: HashSet<&str> = rows.iter().map(|(r, _)| *r).collect();
    println!("unique regions: {}", regions.len());

    // turbofish 写法:链中调用时无需额外标注
    let distinct = "112358"
        .chars()
        .map(|c| c.to_digit(10).unwrap())
        .collect::<HashSet<u32>>();
    println!("distinct digits: {}", distinct.len());
}

Inside the snippet

Collect Iterators Into Maps And Sets is built around the function main.

Putting it to use

Running the file prints labeled results such as eu now:, unique regions:, distinct digits: — each operation’s effect is visible in the output.

Core lines

let regions: HashSet<&str> = rows.iter().map(|(r, _)| *r).collect();
.map(|c| c.to_digit(10).unwrap())
.collect::<HashSet<u32>>();
let ordered: BTreeMap<&str, i32> = rows.clone().into_iter().collect();

Interactive Tools for This Topic

FAQ

What does Collect Iterators Into Maps And Sets print when run?
Running the file directly is enough — expect labeled output lines such as `eu now:`, `unique regions:`, `distinct digits:`.