Hashmaps
The type
HashMap<K, V>stores a mapping of keys of typeKto values of typeVusing a hashing function, which determines how it places these keys and values into memory.For types that implement the
Copytrait, likei32, the values are copied into the hash map. For owned values likeString, the values will be moved and the hash map will be the owner of those values.
hashmaps1.rs
// A basket of fruits in the form of a hash map needs to be defined. The key
// represents the name of the fruit and the value represents how many of that
// particular fruit is in the basket. You have to put at least 3 different
// types of fruits (e.g. apple, banana, mango) in the basket and the total count
// of all the fruits should be at least 5.
use std::collections::HashMap;
fn fruit_basket() -> HashMap<String, u32> {
// TODO: Declare the hash map.
let mut basket = HashMap::new();
// Two bananas are already given for you :)
basket.insert(String::from("banana"), 2);
basket.insert(String::from("apple"), 5);
basket.insert(String::from("mango"), 10);
basket
}
fn main() {
// You can optionally experiment here.
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn at_least_three_types_of_fruits() {
let basket = fruit_basket();
assert!(basket.len() >= 3);
}
#[test]
fn at_least_five_fruits() {
let basket = fruit_basket();
assert!(basket.values().sum::<u32>() >= 5);
}
}I this exercise we just need to declare new
HashMapand insert more entries into it until at least we have5total values.We can define new
HashMaplike this:As you can see we are not defining any types explicitly here because rust will infer it.
But we need to make sure all the keys have the same type and all the values also have the same types.
The we need to add more entries into the hashmap by using
insertmethod.
hashmaps2.rs
In this example we need to insert new fruits if they are not already present in the basket.
We can do this in multiple different ways.
First is by checking if the key exist if not the insert it:
Or we can use
Entrylike this:You can read more about entry in here: https://doc.rust-lang.org/beta/std/collections/hash_map/enum.Entry.html.
hashmaps3.rs
In this example we need to build a score table that contains:
Team Name:
KeyGoals Scored:
TeamScores.goals_scoredGoals Conceded
TeamScores.goals_conceded
There are multiple ways to do this and mostly we will use
Entrybecause its more convenient.First we can use
and_modifywithor_insertlike this:Or by using
or_defaultand then adding the score like this:Which one do you think is better?
Last updated