0

Converting from HashSet<String> to Vec<String> is pretty straightforward:

let hs: HashSet<String> = HashSet::new();
let v: Vec<String> = hs.into_iter().collect();

What's the easiest way to do the same but from a reference to a HashSet?

This doesn't work:

let hs: HashSet<String> = HashSet::new();
let ref_to_hs: &HashSet<String> = &hs;
let v: Vec<String> = ref_to_hs.into_iter().collect();

It results in:

error[E0277]: a value of type `Vec<std::string::String>` cannot be built from an iterator over elements of type `&std::string::String`
at54321
  • 8,726
  • 26
  • 46

1 Answers1

0

OK, I found I can do this:

let v: Vec<String> = ref_to_hs.clone().into_iter().collect();

and it seems to work. Is there, however, a better (more efficient) way to do it?

at54321
  • 8,726
  • 26
  • 46
  • 3
    `ref_to_hs.into_iter().cloned().collect()` will avoid cloning the `HashSet` itself, it will only duplicate the internal strings. – Masklinn Jul 01 '21 at 08:00
  • 1
    @SvenMarnach I just took the snippet and moved the relevant bits around, and it makes no difference, `<&HashSet>::into_iter` delegates to `HashSet::iter`. – Masklinn Jul 01 '21 at 08:14