【问题标题】:How to get the number of keys in a HashMap after inserting or updating a value?插入或更新值后如何获取 HashMap 中的键数?
【发布时间】:2018-03-28 16:50:26
【问题描述】:

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

 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

有没有办法解决这个问题?是不是我写错了?

【问题讨论】:

    标签: rust borrow-checker


    【解决方案1】:

    选择以下之一:

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

    【讨论】:

    • 非常感谢!并感谢您编辑问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多