How can I insert all values of one HashSet into another HashSet?

You don’t want union — as you said, it will create a new HashSet. Instead you can use Extend::extend:

use std::collections::HashSet;

fn main() {
    let mut a: HashSet<u16> = [1, 2, 3].iter().copied().collect();
    let b: HashSet<u16> = [1, 3, 7, 8, 9].iter().copied().collect();

    a.extend(&b);

    println!("{:?}", a); // {8, 3, 2, 1, 7, 9}
}

(Playground)

Extend::extend is also implemented for other collections, e.g. Vec. The result for Vec will differ because Vec does not honor duplicates in the same way a Set does.

Leave a Comment