HashSet<T> to HashSet<&T>

In a function that is working with `HashSet<T>`s, I at some point take a union of two sets like so:

``````let set_union: HashSet<&T> = sets[i].union(&sets[j]).collect();
``````

where `sets` is of type `&Vec<HashSet<T>`. This works well. However, now when I want to later take a union again, I run into a mismatched types error:

``````let set_union_2: HashSet<&T> = set_union.union(&sets[k]).collect();
^^^^^^^^ expected `&T`, found type parameter `T`
``````

I suppose I can `.iter()` the set and then `.collect()` it again, but is there a better way to turn `sets[k]` into a set of type `HashSet<&T>` so that taking a union is possible?

You could just do `set_union.extend(&sets[k])`, in case you don’t need `set_union` anymore. Otherwise, `let mut set_union2 = set_union.clone(); set_union2.extend(&sets[k])`; is probably a decent option.

1 Like