Skip to content
On this page

hashmap1: exercises/hashmaps/hashmaps1.rs

题目

rust
// 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 three different
// types of fruits (e.g apple, banana, mango) in the basket and the total count
// of all the fruits should be at least five.
//
// Make me compile and pass the tests!
//
// Execute `rustlings hint hashmaps1` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

use std::collections::HashMap;

fn fruit_basket() -> HashMap<String, u32> {
    let mut basket = // TODO: declare your hash map here.

    // Two bananas are already given for you :)
    basket.insert(String::from("banana"), 2);

    // TODO: Put more fruits in your basket here.

    basket
}

#[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);
    }
}

我们需要定义一个HashMap来存放一篮子水果,key为水果的名称,value为该水果的数量。

您必须在篮子中放入至少三种不同类型的水果,比如apple, banana, mango等,并且所有水果的总数应该至少要为5个。

修改代码让编译顺利通过。

题目解析

rust
fn fruit_basket() -> HashMap<String, u32> {
    let mut basket = // TODO: declare your hash map here. 
    let mut basket = HashMap::new();  

    // Two bananas are already given for you :)
    basket.insert(String::from("banana"), 2);

    // TODO: Put more fruits in your basket here.
    basket.insert(String::from("apple"), 3); 
    basket.insert(String::from("mongo"), 2); 

    basket
}

参考资料

Powered by VitePress