0

I have solved hashmap2 in the rustlings repository:

fn fruit_basket(basket: &mut HashMap<Fruit, u32>) {
    for fruit in fruit_kinds {
        match fruit {
            Fruit::Apple => basket.entry(Fruit::Apple).or_insert(3),
            Fruit::Banana => basket.entry(Fruit::Banana).or_insert(3),
            Fruit::Mango => basket.entry(Fruit::Mango).or_insert(3),
            Fruit::Lichi => basket.entry(Fruit::Lichi).or_insert(3),
            Fruit::Pineapple => basket.entry(Fruit::Pineapple).or_insert(3),
        };
        // TODO: Put new fruits if not already present. Note that you
        // are not allowed to put any type of fruit that's already
        // present!
    }
}

Now I want to solve it using a different method:

fn fruit_basket(basket: &mut HashMap<Fruit, u32>) {
    for fruit in fruit_kinds {
        match fruit {
            Fruit::Apple => basket.entry(Fruit::Apple).or_insert(3),
            Fruit::Banana => basket.insert(Fruit::Banana, 3),
            Fruit::Mango => basket.entry(Fruit::Mango).or_insert(3),
            Fruit::Lichi => basket.entry(Fruit::Lichi).or_insert(3),
            Fruit::Pineapple => basket.entry(Fruit::Pineapple).or_insert(3),
        };
    }
}

I get this compilation error:

enter image description here

I can understand by reading the documentation that insert returns Option which is causing the issue but don't fully understand how can I fix it.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Kanwar Baweja
  • 183
  • 1
  • 11
  • 2
    [Please do not post errors as images](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question/285557#285557) – Shepmaster Dec 22 '20 at 21:05
  • 1
    It's hard to answer your question because it doesn't include a [MRE]. We can't tell what crates (and their versions), types, traits, fields, etc. are present in the code. It would make it easier for us to help you if you try to reproduce your error on the [Rust Playground](https://play.rust-lang.org) if possible, otherwise in a brand new Cargo project, then [edit] your question to include the additional info. There are [Rust-specific MRE tips](//stackoverflow.com/tags/rust/info) you can use to reduce your original code for posting here. Thanks! – Shepmaster Dec 22 '20 at 21:05
  • [The duplicate applied to your code](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a17fba00a1415d1bf1d8dafc6559d490). TL;DR — each arm of the match must return the same type. Since you don't make use of the returned value, you can use `;` to discard the results, instead producing `()`. – Shepmaster Dec 22 '20 at 21:11

0 Answers0