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.
Code
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
Duplicate Line RemoverFind unique, duplicate, or counted lines with optional case sensitivity and whitespace trimming, all processed locally in the browser.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Dedupe Keeping First Occurrence?
- This is a complete program, not a library excerpt — execution starts at the top.
Report a problem with this exampleOpens a pre-filled issue on GitHub.