Constructing HashSets with matching items

Hi,
I have the following code: Rust Playground

As apparent, I am trying to construct two HashSets to then obtain an iterator of items that are in the first set but not the second.
My issue is that both sets are constructed differently and I have not been able to make the type of items match without cloning.
output_set is a HashSet<&usize> but atom_set is a HashSet<usize> which are not comparable. In the playground I tried adding a reference to the closure in the map but that won't work because it references a temporary value.
My only solution so far has been to clone output_set but that's not ideal since that could be quite large in practice.
Is there an obvious way to convert a usize to &usize that I'm too stupid to see right now?

Btw, calling into_inter on nums is not an option because the vec is needed later for something else.

I think maybe rather than HashSet<&usize> you want simply HashSet<usize> ?

That doesn't work because calling iter on a vector will produce an iterator over references of the vector elements so a HashSet<usize> is impossible to construct like that.
Like I said, I could do HashSet::from_iter(nums.clone().into_iter()) but I'd rather avoid the clone.

nums.iter().copied() has item type usize

2 Likes

I think I got it to work: Rust Playground

Ah this is exactly what I needed. Thanks!
I'm still in the process of getting to know all the functionality of iterators...

That won't do because it moves nums but I need it later. Thanks for the effort though :slight_smile:

You don't have to know the whole standard library by heart. If you don't know about copied, you can just map and then dereference.

Nah you're right but that hadn't occurred to me either. Thanks, however!

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.