HashSet in Rust Programming


Rust also provides us with a HashSet data structure that is mainly used when we want to make sure that no duplicate values are present in our data structure.

If we try to insert a new value into a HashSet that is already present in it, then the previous value gets overwritten by the new value that we inserted

Besides the key features, a HashSet is also used to do the following operations −

  • union − Extract all the unique elements in both sets.
  • difference −G ets all the elements that are present in the first set, but not in the second.
  • intersection − Gets all the elements that are present in both sets.
  • symmertric_difference − Gets all the elements that are in one set or the other, but not in both.

Example

Consider the example shown below −

use std::collections::HashSet;

fn main() {
   let mut a: HashSet = vec![1i32, 2, 3].into_iter().collect();
   let mut b: HashSet = vec![2i32, 3, 4].into_iter().collect();
   assert!(a.insert(4));
   assert!(a.contains(&4));
   // `HashSet::insert()` returns false if value already present  
   assert!(b.insert(4), "Value 4 is already in set B!");
   b.insert(5);
}

In this example, we created a HashSet and then inserted the values in it. If we try to insert values that are already present, then the insert() function will return a false. Hence the above code will return an error.

Output

thread 'main' panicked at 'Value 4 is already in set B!',
src/main.rs:11:5
note: run with `RUST_BACKTRACE=1` environment variable to display
a backtrace

Example

Now let us try to make use of all the methods that are available on a HashSet. Consider the example shown below −

use std::collections::HashSet;
fn main() {
   let mut a: HashSet = vec![1i32, 2, 3].into_iter().collect();
   let mut b: HashSet = vec![2i32, 3, 4].into_iter().collect();
   assert!(a.insert(4));
   assert!(a.contains(&4));
   b.insert(6);
   println!("A: {:?}", a);
   println!("B: {:?}", b);
   println!("Union: {:?}", a.union(&b).collect::>());
   println!("Difference: {:?}",
   a.difference(&b).collect::>());
   println!("Intersection: {:?}",
   a.intersection(&b).collect::>());
   println!("Symmetric Difference: {:?}",
   a.symmetric_difference(&b).collect::>());
}

Output

A: {1, 2, 3, 4}
B: {4, 6, 2, 3}
Union: [1, 2, 3, 4, 6]
Difference: [1]
Intersection: [2, 3, 4]
Symmetric Difference: [1, 6]

Updated on: 03-Apr-2021

288 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements