Idiomatic way to append one hash-set to another

Hi!
I have a two hash-sets and I would like to have one hash-set with the union of the elements in both.
I could think of two ways to do it:

  • Firstly:
let first = ... // First HashSet
let second = ... // Second HashSet
let mut combined = first;
for el in second {
    combined.insert(el);
}
  • Secondly:
let first = ... // First HashSet
let second = ... // Second HashSet
let combined: HashSet<_> = first.union(&second).cloned().collect();

The first method seems clunky, the second one involves cloning.
Is there a better way? (something in the line of Vec::append)

You can use extend: (playground link)

use std::collections::HashSet;


fn main() {
    let mut first = HashSet::new();
    let mut second = HashSet::new();
    first.insert(1);
    second.insert(2);
    let mut combined = first;
    combined.extend(second.into_iter());
    println!("{:?}", combined)
}

Edit:
into_iter() is redundant, this also works:

    combined.extend(second);
3 Likes

Thanks!
Extend is a trait and that's why I couldn't find extend() listed as a method on HashSet. However, as expected, it is listed as a trait that HashSet implements.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.