How to insert an element in a set with Rust

1 Answer

0 votes
use std::collections::HashSet;

fn main() {
    let mut my_set = HashSet::new();

    // Insert elements into the set
    my_set.insert(10);
    my_set.insert(20);
    my_set.insert(30);
    
    my_set.insert(40);
    my_set.insert(40);

    // Check if an element was successfully inserted
    if my_set.insert(20) {
        println!("20 was added to the set.");
    } else {
        println!("20 was already in the set.");
    }

    // Print the set
    println!("{:?}", my_set);
}


    
/*
run:

20 was already in the set.
{20, 30, 40, 10}
   
*/
  
 

 



answered Aug 5, 2025 by avibootz
...