To create a set of numbers from 1 to N in Rust, you can use a for loop to add elements to a HashSet.
In this example,
std::collections::HashSet
module to use HashSet in Rust.HashSet
named number_set
to store the numbers.for
loop to iterate from 1 to 5 and add each number to the set using the insert
method.use std::collections::HashSet;
fn main() {
let mut number_set = HashSet::new();
for i in 1..=5 {
number_set.insert(i);
}
println!("Set of numbers from 1 to 5: {:?}", number_set);
}
Set of numbers from 1 to 5: {1, 2, 3, 4, 5}
In this example,
std::collections::HashSet
module to use HashSet in Rust.HashSet
named number_set
to store the numbers.for
loop to iterate from 1 to 10 and add each number to the set using the insert
method.use std::collections::HashSet;
fn main() {
let mut number_set = HashSet::new();
for i in 1..=10 {
number_set.insert(i);
}
println!("Set of numbers from 1 to 10: {:?}", number_set);
}
Set of numbers from 1 to 10: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
In this tutorial, we learned How to create a Set of Numbers from 1 to N in Rust language with well detailed examples.