rustHow to merge hashsets in Rust
Hashsets in Rust can be merged using the union
method. This method takes two hashsets as arguments and returns a new hashsets containing all the elements from both the hashsets.
Code example:
let mut hs1 = HashSet::new();
hs1.insert(1);
hs1.insert(2);
hs1.insert(3);
let mut hs2 = HashSet::new();
hs2.insert(3);
hs2.insert(4);
hs2.insert(5);
let hs3 = hs1.union(&hs2);
println!("{:?}", hs3);
Output
HashSet { 1, 2, 3, 4, 5 }
Explanation:
let mut hs1 = HashSet::new();
: This line creates a new hashsets calledhs1
hs1.insert(1);
: This line inserts the element1
into the hashsetshs1
let mut hs2 = HashSet::new();
: This line creates a new hashsets calledhs2
hs2.insert(3);
: This line inserts the element3
into the hashsetshs2
let hs3 = hs1.union(&hs2);
: This line creates a new hashsets calledhs3
which contains all the elements from both the hashsetshs1
andhs2
println!("{:?}", hs3);
: This line prints the contents of the hashsetshs3
Helpful links:
More of Rust
- How to match a URL with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to clear a Rust HashMap?
- Yield example in Rust
- Example of yield_now in Rust?
- How to convert a Rust slice to a fixed array?
- How to use regex to match a group in Rust?
- How to convert a Rust HashMap to a BTreeMap?
- How to yield a thread in Rust?
- How to replace strings using Rust regex?
See more codes...