Create empty HashSet, insert elements

HashSet new insert

Rust provides the HashSet struct to hold a set of values. Behind the scenes it is implemented as a HashMap

We can create a new HashSet using the new function. We can declare the type of the values, but in most cases Rust will be able to reason about the value type based on what we inster into it.

If we would like to change the set (e.g. insert elements, remove elements) then we have to defined the variable with the mut keyword to be mutable.

In this example we start with an empty set and then isert values.

As you can observe, inserting the same value more than once does not make a difference on a set. That's because sets only care about values being in or not being in the set.

examples/hashset/create-empty-insert/src/main.rs

use std::collections::HashSet;

fn main() {
    let mut english: HashSet<String> = HashSet::new();
    println!("{:?}", &english);

    english.insert(String::from("chair"));
    println!("{:?}", &english);

    english.insert(String::from("table"));
    println!("{:?}", &english);

    english.insert(String::from("chair"));
    println!("{:?}", &english);

}
{}
{"chair"}
{"chair", "table"}
{"chair", "table"}

Related Pages

Set in Rust using HashSet

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo