Rust Sets

A set, like a vector, is a collection that can contain multiple values of the same type, however, they have the added feature that they cannot contain duplicate values. In Rust there are two types of set, ‘BTreeSet’ and ‘HashSet’, both of which will be discussed here.

The difference between these two types of set is that a ‘HashSet’ doesn’t maintain an order of the items within it, whereas a ‘BTreeSet’ does.

Below is an example of a 'BTreeSet' called 'names', where the 'insert' method is used to add items to the set, then a ‘for’ loop is utilised to display the names.

use std::collections::BTreeSet;

fn main() {

    let mut names = BTreeSet::new();

    names.insert("Bob");
    names.insert("George");
    names.insert("Fred");
    names.insert("Alan");

    for name in names.iter()
    {
        println!("{}", name);
    }

}

The resulting output in the console/terminal displays the names in alphabetical order.

Alan
Bob
Fred
George

Note the 'use' statement above the declaration of the 'main' method. If this wasn't included the 'BTreeSet' would have to be declared as follows.

let mut names = std::collections::BTreeSet::new();

A 'HashSet' can be used in a similar fashion, however, the order of the output isn't guaranteed.

use std::collections::HashSet;

fn main() {

    let mut names = HashSet::new();

    names.insert("Bob");
    names.insert("George");
    names.insert("Fred");
    names.insert("Alan");

    for name in names.iter()
    {
        println!("{}", name);
    }

}

As previously mentioned, a set cannot contain duplicate items, however, if an attempt is made to add a duplicate, no error is produced, and no new item gets added.

Both types of set contain a 'remove' method that, as the name suggests, can be used to remove an item from a set.

names.remove("George");

In order to find out how many items are in a set, the 'len' method can be used.

println!("{}", names.len());

To check if a specified value exists within a set, the 'contains' method can be utilised.

if names.contains(&"Bob")
{
    println!("The value 'Bob' is in the set.");
}
else
{
    println!("The value 'Bob' is not in the set.");
}