Rust Program to Iterate over a Set


Iterate over a Set

Rust Programming Language


Iterate over a Set


Problem


Rust program that iterates over a HashSet.

Input


use std::collections::HashSet;

fn main() {
    let set: HashSet<i32> = vec![1, 2, 3, 4, 5].into_iter().collect();
    
    println!("Set: {:?}", set);
    
    for item in &set {
        println!("{}", item);
    }
}{codeBox}

Output


Set: {1, 2, 3, 4, 5}
1
2
3
4
5{codeBox}

Explanation


In this example, we create a HashSet<i32> called set by converting a Vec<i32> into a HashSet<i32> using the into_iter and collect methods.

We then print the contents of the set using println!("Set: {:?}", set);.

Finally, we iterate over the set using a for loop and print each item using println!("{}", item);. Note that we use a reference to the set (&set) in the for loop to avoid taking ownership of the set.

This shows the contents of the set, followed by each item printed on a separate line in the order they were added to the set. Note that the order of iteration is not guaranteed for HashSets.


Post a Comment