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

This example demonstrates how to use hashset basic in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

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

More Collections Examples