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
- Hashshet example in Rust
- How to convert Rust bytes to hex?
- How to convert a Rust HashMap to a JSON string?
- How to convert a Rust HashMap to JSON?
- How to get the last element of a Rust slice?
- How to use non-capturing groups in Rust regex?
- How to use groups in a Rust regex?
- How to match the end of a line in a Rust regex?
- How to escape dots with regex in Rust?
- How to use regex to match a group in Rust?
See more codes...