HashSet in Rust
Membership and set algebra, with no duplicate values by construction.
use std::collections::HashSet;
fn main() {
let a: HashSet<i32> = [1, 2, 3, 4].into_iter().collect();
let b: HashSet<i32> = [3, 4, 5].into_iter().collect();
let mut both: Vec<&i32> = a.intersection(&b).collect();
both.sort();
println!("{:?}", both);
let mut only_a: Vec<&i32> = a.difference(&b).collect();
only_a.sort();
println!("{:?}", only_a);
let mut seen = HashSet::new();
println!("{} {}", seen.insert("fig"), seen.insert("fig"));
}
How it works
insertreturns false when the value was already present.intersectionanddifferenceyield iterators, not sets.collectbuilds a set straight from an iterator.
Keywords and builtins used here
HashSetVecfni32letmainmutuse
The run, in numbers
- Lines
- 17
- Characters to type
- 441
- Tokens
- 172
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 115 seconds.
Step 6 of 8 in Collections, step 35 of 39 in Language basics.