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 get a capture group using Rust regex?
- How to use regex with bytes in Rust?
- How to match a URL with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to use Unicode in a regex in Rust?
- How to get all matches from a Rust regex?
- How to match a string with regex in Rust?
- How to use regex to match a group in Rust?
- How to use regex to match a double quote in Rust?
- How to calculate the inverse of a matrix in Rust?
See more codes...