Using a HashSet
The best way to describe a HashSet
is by describing how it's implemented: HashMap<K, ()>
. It's just a HashMap
without any values!
The two best reasons to choose a HashSet
are:
- You don't want to deal with duplicate values at all, as it doesn't even include them.
- You plan on doing a lot (and I mean a lot) of item lookup - that is the question, Does my collection contain this particular item?. In a vector, this is done in , while a
HashSet
can do it in.
How to do it...
- In the folder
src/bin
, create a file calledhashset.rs
. - Add the following code, and run it with
cargo run --bin hashset
:
1 use std::collections::HashSet; 2 3 fn main() { 4 // Most of the interface of HashSet 5 // is the same as HashMap, just without 6 // the methods that handle values 7 let mut books = HashSet::new(); 8 books.insert("Harry Potter and the Philosopher's Stone"); 9 books.insert("The Name of the Wind"); 10 books.insert("A Game of Thrones"); 11 12 // A HashSet will...