gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:58:36 26 4
gpt4 key购买 nike

我想在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. 添加一个 block 来限制借用:

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

关于rust - 如何在插入或更新值后获取 HashMap 中的键数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49540139/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com