我正在尝试构建一个哈希图,该哈希图计算字符串中的字符频率。我的方法是将字符串中的字符折叠起来,在每次迭代时增加当前字符的计数。不幸的是,铁锈告诉我我在借贷上做错了。
使用clone()
或将hm.get(&c)
分解为单独的一行均无效。
我看不出如何避免有关两阶段借阅的错误。 (relevant rust-lang github issue)
use std::collections::HashMap;
fn main() {
let some_str = "some string";
let hm = some_str.chars().fold(HashMap::new(), |mut hm, c| {
match hm.get(&c) {
None => hm.insert(c, 1),
Some(i) => hm.insert(c, i + 1),
};
hm
});
for (key, val) in hm.iter() {
println!("{}: {}", key, val);
}
}
给出此错误
warning: cannot borrow `hm` as mutable because it is also borrowed as immutable
--> dank.rs:9:24
|
7 | match hm.get(&c) {
| -- immutable borrow occurs here
8 | None => hm.insert(c, 1),
9 | Some(i) => hm.insert(c, i+1)
| ^^ - immutable borrow later used here
| |
| mutable borrow occurs here
|
= note: `#[warn(mutable_borrow_reservation_conflict)]` on by default
= warning: this borrowing pattern was not meant to be accepted, and may become a hard error in the future
= note: for more information, see issue #59159 <https://github.com/rust-lang/rust/issues/59159>
向@Stargateur提供我的问题的答案