RRust By Example
beginnerCollections

HashSet Basic

Use HashSets for unique collections and set operations.

HashSet Basic

Use HashSets for unique collections and set operations.

Difficulty

Beginner

Code

rust
use std::collections::HashSet;

fn main() {
    let mut a: HashSet<i32> = vec![1, 2, 3, 4].into_iter().collect();
    let b: HashSet<i32> = vec![3, 4, 5, 6].into_iter().collect();

    println!("union: {:?}", a.union(&b).collect::<Vec<_>>());
    println!("intersection: {:?}", a.intersection(&b).collect::<Vec<_>>());
    println!("difference: {:?}", a.difference(&b).collect::<Vec<_>>());

    a.insert(5);
    println!("a contains 5: {}", a.contains(&5));
}

Explanation

HashSet stores unique values with set operations.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the collections category to build a complete understanding of this topic.

More Collections Examples