如何修正Rust代码使HashMap统计不可变vector元素出现次数?
Rust哈希表统计元素出现次数的编译错误修复
目标是用HashMap统计aux_vec_i32中各元素的出现次数,以下是原代码、编译错误分析及修复方案:
原代码
use std::collections::HashMap; fn main(){ struct Data{ the_data: i32, } let aux_vec_i32 = vec![1, 2, 3, 1]; let mut hmap_for_data: HashMap<i32, Data>=HashMap::new(); for i in &aux_vec_i32 { match hmap_for_data.get(&mut aux_vec_i32[*i as usize]) { None => { hmap_for_data.insert( aux_vec_i32[*i as usize], Data { the_data: 1, } ); } Some(mut data_to_increment) => { data_to_increment.the_data += 1; } } } }
编译错误信息
error[E0502]: cannot borrow `aux_vec_i32` as mutable because it is also borrowed as immutable --> src/main.rs:11:38 | 10 | for i in &aux_vec_i32 { | ------------ | | | immutable borrow occurs here | immutable borrow later used here 11 | match hmap_for_data.get(&mut aux_vec_i32[*i as usize]) { | ^^^^^^^^^^^ mutable borrow occurs here error[E0596]: cannot borrow `aux_vec_i32` as mutable, as it is not declared as mutable --> src/main.rs:11:38 | 11 | match hmap_for_data.get(&mut aux_vec_i32[*i as usize]) { | ^^^^^^^^^^^ cannot borrow as mutable | help: consider changing this to be mutable | 7 | let mut aux_vec_i32 = vec![1, 2, 3, 1]; | +++ error[E0594]: cannot assign to `data_to_increment.the_data`, which is behind a `&` reference --> src/main.rs:21:17 | 20 | Some(mut data_to_increment) => { | --------------------- consider changing this binding's type to be: `&mut Data` 21 | data_to_increment.the_data += 1; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `data_to_increment` is a `&` reference, so the data it refers to cannot be written
错误核心原因
- 完全无需操作原数组
aux_vec_i32获取哈希表key,遍历得到的i就是目标统计元素,直接用它作为key即可。 HashMap::get返回不可变引用,无法修改内部数据;要修改需用get_mut,或更高效的entryAPI。- 错误尝试对不可变的
aux_vec_i32进行可变借用,违反Rust借用规则。
修复后的代码
use std::collections::HashMap; fn main(){ struct Data{ the_data: i32, } let aux_vec_i32 = vec![1, 2, 3, 1]; let mut hmap_for_data: HashMap<i32, Data> = HashMap::new(); for &num in &aux_vec_i32 { // 用entry API统一处理key存在/不存在的情况 let data = hmap_for_data.entry(num).or_insert(Data { the_data: 0 }); data.the_data += 1; } // 可选:验证统计结果 for (key, val) in hmap_for_data { println!("元素{}出现{}次", key, val.the_data); } }
修复说明
- 遍历直接取
&num,拿到数组元素值作为哈希表key,无需操作原数组。 HashMap::entry方法:若key不存在则插入初始值Data { the_data: 0 },若存在则返回对应值的可变引用。- 直接对可变引用指向的
the_data自增,符合Rust借用规则,同时代码更简洁高效。
内容的提问来源于stack exchange,提问作者branco
相关产品推荐
相关产品推荐

