how do i create a hashset from a borrowed array of a generic type in rust?

To use HashSet your function needs to have the Eq and Hash trait bounds:

use std::hash::Hash;
use std::collections::HashSet;

pub fn sublist<T: Eq + Hash>(first_list: &[T], second_list: &[T]) -> bool {
  let first_set: HashSet<&T> = first_list.iter().collect();
  let second_set: HashSet<&T> = second_list.iter().collect();

  first_set.is_subset(&second_set)
}

If you only know that T is PartialEq, then you can implement it like so:

pub fn sublist<T: PartialEq>(first_list: &[T], second_list: &[T]) -> bool {
    first_list.iter().all(|v| second_list.contains(v))
}

Other options include T: Ord and use BTreeSet.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top