rustHow to compare two HashSets in Rust?
Comparing two HashSets in Rust is easy and efficient. The HashSet::is_subset
and HashSet::is_superset
methods can be used to compare two HashSets.
Example code
let set_a: HashSet<i32> = [1, 2, 3].iter().cloned().collect();
let set_b: HashSet<i32> = [2, 3, 4].iter().cloned().collect();
assert!(set_a.is_subset(&set_b));
assert!(!set_b.is_subset(&set_a));
Output example
assertion successful
assertion successful
Code explanation
let set_a: HashSet<i32> = [1, 2, 3].iter().cloned().collect();
- This line creates aHashSet
calledset_a
with elements1
,2
, and3
.let set_b: HashSet<i32> = [2, 3, 4].iter().cloned().collect();
- This line creates aHashSet
calledset_b
with elements2
,3
, and4
.assert!(set_a.is_subset(&set_b));
- This line checks ifset_a
is a subset ofset_b
.assert!(!set_b.is_subset(&set_a));
- This line checks ifset_b
is not a subset ofset_a
.
Helpful links
Related
More of Rust
- How to implement PartialEq for a Rust HashMap?
- How to use regex to match a group in Rust?
- How to use regex to match a double quote in Rust?
- How to get all values from a Rust HashMap?
- How to convert JSON to a struct in Rust?
- How to get an entry from a HashSet in Rust?
- How to convert a Rust HashMap to a BTreeMap?
- How to match digits with regex in Rust?
- How to declare a matrix in Rust?
- How to convert a u8 slice to a hex string in Rust?
See more codes...