Intersection of hashsets

Hi.

I need to get the intersection of several sets of indexes into a vector (usize). However, I can't get the code to deploy. This minimal example won't compile:

let search_set : HashSet<usize> = HashSet::new();
let part_result : HashSet<usize> = HashSet::new();

let intersection : HashSet<usize> = search_set.intersection(&part_result).collect();

This gives me the following errors:

a collection of type std::collections::HashSet<usize> cannot be built from an iterator over elements of type &usize

a collection of type std::collections::HashSet<usize> cannot be built from std::iter::Iterator<Item=&usize>

help: the trait std::iter::FromIterator<&usize> is not implemented for std::collections::HashSet<usize>

and:

a collection of type std::collections::HashSet<usize> cannot be built from std::iter::Iterator<Item=&usize>

I've tried to implement the FromIterator<&usize> for HashSet but got blocked by the compiler.

I'm also confused why the internal type is &usize? Is this because the hashsets owns the internally-held usizes, so the type is a reference? But shouldn't the HashSet store them in continous memory? Having a reference for each usize seems... slow?

I'm rather new to rust, so apologies if this is completely basic stuff.

  • Dan

The message is about .collect(). It never wants you to actually make an implementation. It tries to say that elements you have as an input - &usize are not the same as the element type you demand in the output - usize.

Just change &usize to usize with .copied() adaptor:

let intersection : HashSet<usize> = search_set.intersection(&part_result).copied().collect();

You get &usize in the first place, because intersection picks elements from two hashsets by reference (it avoids cloning in case the elements were big/expensive to clone, and without cloning you get to work with references).

1 Like

It avoids cloning to also support types that can't be cloned. Such as unique references, or MutexGuard

Thanks!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.