phuc hung
phuc hung

Reputation: 21

I dont't understand about how hashmap put value in?

Code 1:

let mut scores = HashMap::new();
let x = scores.entry(String::from("MC")).or_insert(10);
println!("{:?}",scores);
println!("x={}",x);

Code 2:

let text = "this world is a wonder full world";
let mut map = HashMap::new();
println!("{:?}",text.split_whitespace());
for i in text.split_whitespace(){
    let count =  map.entry(i).or_insert(0);
    *count +=1;
}
println!("{:?}",map);

I have 2 questions:

Upvotes: 0

Views: 60

Answers (1)

Netwave
Netwave

Reputation: 42678

Why is the scores in code 1 can't be print but the map in code 2 can be print?

Lets look at the compiler error:

error[E0502]: cannot borrow `scores` as immutable because it is also borrowed as mutable
 --> src/main.rs:7:22
  |
5 |     let x = scores.entry(String::from("MC")).or_insert(10);
  |             ------ mutable borrow occurs here
6 | 
7 |     println!("{:?}", scores);
  |                      ^^^^^^ immutable borrow occurs here
8 |     println!("x={}", x);
  |                      - mutable borrow later used here

You are taking a mutable reference on x and an inmutable one in the first print to the same thing. This is invalid by rust borrowing rules. One way of changing it would be to use a custom scope so the mut reference is dropped after used:

use std::collections::HashMap;
fn main() {
    let mut scores = HashMap::new();
    {
        let x = scores.entry(String::from("MC")).or_insert(10);
        println!("x={}", x);
    }
    println!("{:?}", scores);
}

Playground

In there x is droped after the scope is finish so it validates referencing scores again.

As per:

In code 2, what is the purpose of count?

*count +=1; just updates the corresponding item in the Hashmap by increasing its value by 1. Basically it is counting words. If you remove it, then, for any word you are just creating a default value of 0 at map.entry(i).or_insert(0).

Upvotes: 2

Related Questions