Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Basic Set operations in Rust

  • set

  • HashSet

  • insert

  • remove

  • contains

  • A HashSet can be used for the mathematical SET operations.

  • We can insert values. The HashSet will only contain one copy of each value regardless the number of times we insert it.

  • We can remove values.

  • We can get the number of elements in the set using len.

  • We can check if a set contains a certain value.

  • There is no order among the elements so when we print them they might be in any order.

use std::collections::HashSet;

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

    english.insert(String::from("chair"));
    println!("{:?}", &english);
    assert_eq!(english.len(), 1);
    assert_eq!(format!("{:?}", &english), r#"{"chair"}"#);

    english.insert(String::from("table"));
    println!("{:?}", &english);
    assert_eq!(english.len(), 2);
    assert!(
        format!("{:?}", &english) == r#"{"table", "chair"}"#
            || format!("{:?}", &english) == r#"{"chair", "table"}"#
    );

    english.insert(String::from("chair"));
    println!("{:?}", &english);
    assert_eq!(english.len(), 2);
    assert!(
        format!("{:?}", &english) == r#"{"table", "chair"}"#
            || format!("{:?}", &english) == r#"{"chair", "table"}"#
    );

    assert!(english.contains("chair"));
    assert!(!english.contains("door"));
    assert_eq!(english.len(), 2);

    println!("----");
    for word in &english {
        println!("{}", word);
    }
    println!("----");

    english.remove("chair");
    println!("{:?}", &english);
    assert_eq!(english.len(), 1);
    assert_eq!(format!("{:?}", &english), r#"{"table"}"#);
}
{}
{"chair"}
{"chair", "table"}
{"chair", "table"}
----
chair
table
----
{"table"}