Rust Maps
A map in Rust is a collection that stores information in key and value pairs. When compared to a physical dictionary, the word would be the key, whilst the description would be the value. The keys are similar to values in a set in that they must be unique, with the value able to be duplicated if required. The other similarity with a set is that there are two types of map, a 'BTreeMap' and a 'HashMap'. Similar to a 'BTreeSet' and a 'HashSet', A 'BTreeMap' is ordered by the key, whereas a 'HashMap' doesn't maintain an order.
Below is an example of a 'BTreeMap' called 'people', where a person's name is the key and their age is the value. The key and value pairs are added to the map using the 'insert' method. A ‘for’ loop is then used to display the key and value of each pair as part of a sentence.
use std::collections::BTreeMap; fn main() { let mut people = BTreeMap::new(); people.insert("Bob Smith", 30); people.insert("George Jones", 21); people.insert("Fred Bloggs", 43); people.insert("Alan White", 29); for (key, val) in people.iter() { println!("{} is {} years old.", key, val); } }
The resulting output in the console/terminal displays the names in alphabetical order.
Alan White is 29 years old. Bob Smith is 30 years old. Fred Bloggs is 43 years old. George Jones is 21 years old.
A 'HashMap' can be used in a similar fashion, however, the order of the output isn't guaranteed.
use std::collections::HashMap; fn main() { let mut people = HashMap::new(); people.insert("Bob Smith", 30); people.insert("George Jones", 21); people.insert("Fred Bloggs", 43); people.insert("Alan White", 29); for (key, val) in people.iter() { println!("{} is {} years old.", key, val); } }
As previously mentioned, a map cannot contain duplicate keys, however, if an attempt is made to add a duplicate, no error is produced, and no new item gets added.
Both types of map contain a 'remove' method that, as the name suggests, can be used to remove a key and value pair from a map.
people.remove("George Jones");
In order to find out how many key and value pairs are in a map, the 'len' method can be used.
println!("{}", people.len());
To check if a specified key exists within a map, the 'contains_key' method can be utilised.
if people.contains_key(&"Bob Smith") { println!("The key 'Bob Smith' is in the map."); } else { println!("The key 'Bob Smith' is not in the map."); }