访问另一个哈希图中的非可变哈希图

时间:2019-02-17 00:48:29

标签: rust

基本上我得到的是一个哈希图,它具有另一个哈希图作为其值。

我刚开始生锈,所以当我尝试编译器抱怨neighbors不可变时,我想做的就是将其插入到已经存在的hashmap中。

但是,如果我通过进行Some(mut neighbors) => {使它可变,则会出现另一个错误:

error[E0596]: cannot borrow `*neighbors` as mutable, as it is behind a `&` reference
  --> src\main.rs:24:13
   |
23 |         Some(mut neighbors) => {
   |              ------------- help: consider changing this to be a mutable reference: `&mut std::collections::HashMap<u32, bool>`
24 |             neighbors.insert(j, true);
   |             ^^^^^^^^^ `neighbors` is a `&` reference, so the data it refers to cannot be borrowed as mutable

令人困惑的是,我正在插入一个可变引用,因此我希望它保持可变。

下面是完整的代码:

use std::collections::HashMap;

fn main() {
    let matrix = HashMap::new();
    let step1 = add_edge(matrix, 1, 2);
    let step2 = add_edge(step1, 5, 1);
    let step3 = add_edge(step2, 5, 2);
    let step4 = add_edge(step3, 2, 6);

    for (&i, secondLevel) in step4.iter() {
        for (&j, &value) in secondLevel.iter() {
            println!("Calling {}, {}: {}", i, j, value);
        }
    }
}

fn add_edge(
    mut matrix: HashMap<u32, HashMap<u32, bool>>,
    i: u32,
    j: u32,
) -> HashMap<u32, HashMap<u32, bool>> {
    match matrix.get(&i) {
        Some(neighbors) => {
            neighbors.insert(j, true);
        }
        _ => {
            let mut neighbors = HashMap::new();
            neighbors.insert(j, true);
            matrix.insert(i, neighbors);
        }
    }

    match matrix.get(&j) {
        Some(neighbors) => {
            neighbors.insert(i, true);
        }
        _ => {
            let mut neighbors = HashMap::new();
            neighbors.insert(i, true);
            matrix.insert(j, neighbors);
        }
    }

    return matrix;
}

0 个答案:

没有答案