Using a HashMap
If you imagine a Vec
as a collection that assigns an index (0, 1, 2, and so on) to data, the HashMap
is a collection that assigns any data to any data. It allows you to map arbitrary, hashable data to other arbitrary data. Hashing and mapping, that's where the name comes from!
How to do it...
- In the folder
src/bin
, create a file calledhashmap.rs
. - Add the following code, and run it with
cargo run --bin hashmap
:
1 use std::collections::HashMap; 2 3 fn main() { 4 // The HashMap can map any hashable type to any other 5 // The first type is called the "key" 6 // and the second one the "value" 7 let mut tv_ratings = HashMap::new(); 8 // Here, we are mapping &str to i32 9 tv_ratings.insert("The IT Crowd", 8); 10 tv_ratings.insert("13 Reasons Why", 7); 11 tv_ratings.insert("House of Cards", 9); 12 tv_ratings.insert("Stranger Things", 8); 13 tv_ratings.insert("Breaking Bad", 10); 14 15 // Does a key exist? 16 let contains_tv_show ...