To get the size of a set in Rust, you can use the len
method on the set.
In this example,
set1
using the HashSet
type from the std::collections
module with some elements.len
method on the set object set1
to get the number of elements in the set.len
method returns the size of the set.use std::collections::HashSet;
fn main() {
let mut set1 = HashSet::new();
set1.insert("apple");
set1.insert("banana");
set1.insert("cherry");
let size = set1.len();
println!("Size of set1: {}", size);
}
Size of set1: 3
In this example,
empty_set
using the HashSet
type from the std::collections
module.len
method on the set object empty_set
to get the number of elements in the set.len
method returns 0.use std::collections::HashSet;
fn main() {
let empty_set: HashSet<&str> = HashSet::new();
let size = empty_set.len();
println!("Size of empty_set: {}", size);
}
Size of empty_set: 0
In this tutorial, we learned How to Get Length of a Set in Rust language with well detailed examples.