To sort the items of a set in Rust, you can convert the set to a vector and then sort the vector using the sort()
method.
In this example,
numbers
containing some integer elements using the hashset!
macro.into_iter()
method.sort()
method.use std::collections::HashSet;
fn main() {
let numbers = hashset![5, 3, 1, 4, 2];
let mut sorted_numbers: Vec<_> = numbers.into_iter().collect();
sorted_numbers.sort();
println!("Sorted numbers:");
for number in sorted_numbers {
println!("{}", number);
}
}
Sorted numbers: 1 2 3 4 5
In this example,
fruits
containing some string elements using the hashset!
macro.into_iter()
method.sort()
method.use std::collections::HashSet;
fn main() {
let fruits = hashset!['Banana', 'Apple', 'Cherry', 'Date'];
let mut sorted_fruits: Vec<_> = fruits.into_iter().collect();
sorted_fruits.sort();
println!("Sorted fruits:");
for fruit in sorted_fruits {
println!("{}", fruit);
}
}
Sorted fruits: Apple Banana Cherry Date
In this tutorial, we learned How to Sort Items of a Set in Rust language with well detailed examples.