std-method

HashSet::difference

Yield elements in self that do not occur in other. Difference is directional; switching operands can change the result. Expected stdout (not executed): [1, 3] Common mistake: Using difference for elements present in exactly one of either set.

Formal Syntax & Structure

rust syntaxrust
pub fn difference<'a>(&'a self, other: &'a HashSet<T, S>) -> Difference<'a, T, S>

Working Example

Example Snippetrust
fn main() {    use std::collections::HashSet;    let required = HashSet::from([1, 2, 3]);    let done = HashSet::from([2, 4]);    let mut missing: Vec<_> = required.difference(&done).copied().collect();    missing.sort_unstable();    println!("{missing:?}");}
Rust Reference