Table of content

Set in Rust

A Set is an abstract data type. A concept is derived from a set theory of mathematics. Similar to an array, it is a data structure composed of different elements. The difference lies in the collection of some important characteristics:

  • Disorder: It is not important that no specific ordering or ordering of elements within a collection.
  • Dissimilarity: Each element in a collection can only appear once.

In general, the implementation of the set will be as close as possible to the finite set definition in set theory. This implementation also follows the mathematical definition.

Basic operation

As a container, the collection has the following basic operations:

  • new : Initialize a collection.
  • contains : Check for specific elements in the collection.
  • is_empty : Check if there are no elements in the collection.
  • insert : Add an element.
  • remove : Remove specific elements.
  • len : Check the number of elements in the collection.
  • iter : Produces an iterator of all the elements in the iteration set.
impl<T> HashSet<T>
where T: Hash + Eq,
{ pub fn len(&self) -> usize { self.hash_map.len() }

pub fn is_empty(&self) -> bool { self.hash_map.is_empty() }

pub fn insert(&mut self, value: T) -> bool { // 1 self.hash_map.insert(value, ()).is_none() }

pub fn contains<Q>(&self, value: &Q) -> bool // 2 where T: Borrow<Q>, Q: Hash + Eq + ?Sized, { self.hash_map.get(value).is_some() }

pub fn remove<Q>(&mut self, value: &Q) -> bool // 3 where T: Borrow<Q>, Q: Hash + Eq + ?Sized, { self.hash_map.remove(value).is_some() }

pub fn iter(&self) -> impl Iterator<Item = &T> { // 4 self.hash_map.iter().map(|(k, _)| k) } }

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions