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 calledhs1hs1.insert(1);: This line inserts the element1into the hashsetshs1let mut hs2 = HashSet::new();: This line creates a new hashsets calledhs2hs2.insert(3);: This line inserts the element3into the hashsetshs2let hs3 = hs1.union(&hs2);: This line creates a new hashsets calledhs3which contains all the elements from both the hashsetshs1andhs2println!("{:?}", hs3);: This line prints the contents of the hashsetshs3
Helpful links:
More of Rust
- Regex example to match multiline string in Rust?
- How to use regex captures in Rust?
- How to use binary regex in Rust?
- How to print a Rust HashMap?
- How to use regex to match a double quote in Rust?
- How to replace a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to match a URL with a regex in Rust?
- How to use regex with bytes in Rust?
- How to make regex case insensitive in Rust?
See more codes...