cob*_*bie 2 rust borrow-checker
当使用cargo build编译以下代码片段时,借用检查器似乎很好,但是使用rustc时出现错误
error[E0502]: cannot borrow `char_counts` as mutable because it is also borrowed as immutable
--> src/lib.rs:14:17
|
10 | let count = char_counts.get(&char);
| ----------- immutable borrow occurs here
...
14 | char_counts.insert(char, rem);
| ^^^^^^^^^^^ mutable borrow occurs here
...
19 | }
| - immutable borrow ends here
Run Code Online (Sandbox Code Playgroud)
任何想法为什么会发生这种情况?
use std::collections::HashMap;
pub fn anagram(word: &str, another_word: &str) -> i32 {
let mut char_counts = HashMap::new();
for char in word.chars() {
let count = char_counts.entry(char).or_insert(0);
*count += 1;
}
for char in another_word.chars() {
let count = char_counts.get(&char);
if let Some(val) = count {
let rem = val - 1;
if rem > 0 {
char_counts.insert(char, rem);
} else {
char_counts.remove(&char);
}
}
}
println!("{:?}", char_counts);
return char_counts.keys().len() as i32;
}
Run Code Online (Sandbox Code Playgroud)
cargo --version和rustc --version命令都输出1.33
| 归档时间: |
|
| 查看次数: |
100 次 |
| 最近记录: |