std-method

HashSet::symmetric_difference

Yield elements that occur in one set but not both. This is useful for detecting additions and removals together. Expected stdout (not executed): [1, 4] Common mistake: Using it when only newly added elements are wanted.

Formal Syntax & Structure

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

Working Example

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