如何在插入或更新值后获取 HashMap 中的键数?

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

我想在map中插入或更新一个值,然后获取键的个数。

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

编译器错误:

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

有什么办法可以解决这个问题吗?是不是我写错了?

选择其中一项:

  1. 使用 Rust 2018 或其他版本的 Rust 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. 不要创建临时值:

    *map.entry("Tom").or_insert(0) += 1;
    
  3. 添加块以限制借用:

    {
        let count = map.entry("Tom").or_insert(0);
        *count += 1;
    }