Dedupe Keeping First Occurrence

Filter an iterator through a HashSet whose insert return flags first sightings, so duplicates drop while the original order of survivors is preserved.

RustData Integrity

Code

rustsnippet
22 lines
use std::collections::HashSet;

fn main() {
    // dedupe: keep first occurrence, drop later duplicates
    let tags = vec!["go", "rust", "go", "sql", "rust", "go"];
    let mut seen = HashSet::new();
    let deduped: Vec<&str> = tags
        .iter()
        .copied()
        .filter(|tag| seen.insert(tag))
        .collect();
    println!("{deduped:?}");

    let mut seen = HashSet::new();
    let scores = [7, 7, 3, 9, 3, 7];
    let unique_scores: Vec<i32> = scores
        .iter()
        .copied()
        .filter(|score| seen.insert(*score))
        .collect();
    println!("{unique_scores:?}");
}

Dedupe Keeping First Occurrence, line by line

Everything happens inside the function main.

Points of care

  • Every referenced symbol is a language built-in — nothing to download.

Using it

Entry signature: fn main()

Key statements

.filter(|score| seen.insert(*score))
.collect();
.filter(|tag| seen.insert(tag))
.collect();

Interactive Tools for This Topic

FAQ

How do you run Dedupe Keeping First Occurrence?
This is a complete program, not a library excerpt — execution starts at the top.