Hashmaps

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 HashMap and insert more entries into it until at least we have 5 total values.

  • We can define new HashMap like 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 insert method.

hashmaps2.rs

hashmaps3.rs

  • In this example we need to build a score table that contains:

    • Team Name: Key

    • Goals Scored: TeamScores.goals_scored

    • Goals Conceded TeamScores.goals_conceded

  • There are multiple ways to do this and mostly we will use Entry because its more convenient.

  • First we can use and_modify with or_insert like this:

  • Or by using or_default and then adding the score like this:

  • Which one do you think is better?

Last updated