Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the number of keys in a HashMap after inserting or updating a value?

I want to insert or update a value in the map, and then get the number of keys.

 use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    let count = map.entry("Tom").or_insert(0);
    *count += 1;

    let size = map.keys().len();
    println!("{} men found", size);
}

The compiler error:

error[E0502]: cannot borrow `map` as immutable because it is also borrowed as mutable
  --> src/main.rs:8:16
   |
5  |     let count = map.entry("Tom").or_insert(0);
   |                 --- mutable borrow occurs here
...
8  |     let size = map.keys().len();
   |                ^^^ immutable borrow occurs here
9  |     println!("{} men found", size);
10 | }
   | - mutable borrow ends here

Is there any way to work around this? Is the way I wrote it wrong?

like image 732
Kenneth Avatar asked Mar 28 '18 16:03

Kenneth


People also ask

How do you count the number of entries in a HashMap?

Use the size() method to get the count of elements.

How do you find out the number of key-value mappings present in a HashMap?

HashMap. size() method of HashMap class is used to get the size of the map which refers to the number of the key-value pair or mappings in the Map. Parameters: The method does not take any parameters. Return Value: The method returns the size of the map which also means the number of key-value pairs present in the map.

Can you get a HashMap key with a value?

HashMap can contain null for key and value HashMap can contain null for key and value.

What happens if we update the key object that is in a HashMap?

When you mutate a key which is already present in the HashMap you break the HashMap . You are not supposed to mutate keys present in the HashMap .


1 Answers

Choose one of:

  1. Use Rust 2018 or another version of Rust with non-lexical lifetimes:

    use std::collections::HashMap;
    
    fn main() {
        let mut map = HashMap::new();
        let count = map.entry("Tom").or_insert(0);
        *count += 1;
    
        let size = map.keys().len();
        println!("{} men found", size);
    }
    
  2. Don't create a temporary value:

    *map.entry("Tom").or_insert(0) += 1;
    
  3. Add a block to constrain the borrow:

    {
        let count = map.entry("Tom").or_insert(0);
        *count += 1;
    }
    
like image 197
Shepmaster Avatar answered Oct 26 '22 09:10

Shepmaster