HashSet for membership
Quick answer
A set stores distinct values. Use HashSet<T> to check whether something has already been seen or to remove duplicates when order does not matter.
Insertion and set operations
insert returns true for a new element and false for an existing one. contains checks membership. Intersection yields elements common to two sets. The iterator order is unspecified; compare membership or counts, or sort collected elements for display.
use std::collections::HashSet;fn main() { let mut seen = HashSet::new(); for id in [4, 7, 4] { println!("new: {}", seen.insert(id)); }}Expected stdout (not executed):
new: truenew: truenew: falseThe third insertion does not add a new element.
use std::collections::HashSet;fn main() { let a = HashSet::from([1, 2, 3]); let b = HashSet::from([2, 3, 4]); println!("shared: {}", a.intersection(&b).count());}Expected stdout (not executed):
shared: 2Counting avoids reliance on order.
Common mistake
A set is not a map; it cannot attach a separate value to each key.
Try it yourself
Check whether two lists share a particular ID and count their union.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HashSet for membership — practice quiz
Choose one answer per question, then review the explanation.
What does the second `set.insert(9)` return if 9 was already inserted?
What is the intersection of sets {1, 3} and {3, 4}?
Which question is directly answered by HashSet::contains?