Skip to content

Find the First Duplicate Value

Walk a slice and return the first value that is already in a HashSet, using insert's false-on-duplicate result inside find.

Language: Rust

Added on: 21st August 2026

use std::collections::HashSet;
use std::hash::Hash;

fn first_duplicate<T: Copy + Eq + Hash>(items: &[T]) -> Option<T> {
    let mut seen = HashSet::new();
    items.iter().copied().find(|x| !seen.insert(*x))
}

Caveats

Needs T: Copy + Eq + Hash. Returns None when every value is unique.