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

12

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

 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个回答

15

选择以下之一:

  1. 使用Rust 2018或其他具有非词法生命周期的版本:

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);
}
  • 不要创建临时值:

    *map.entry("Tom").or_insert(0) += 1;
    
  • 添加一个块来限制借用:

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

    1
    非常感谢!并且感谢您对问题的编辑! - Kenneth

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接