关于rust:HashMap出现Struct错误:无法借用可变引用“&”中的数据

HashMap in a Struct error: cannot borrow data in a “&” reference as mutable

我有以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
struct Node{
    node_map: HashMap<char, Node>,
    value: Option<i32>,
}

struct Trie {
    root: Node,
}

impl Trie {
    fn new() -> Trie {
        Trie {
            root: Node{
                node_map: HashMap::new(),
                value: None,
            },
        }
    }

    fn find(&self, key: &String) -> Option<&Node> {
       // Returning some Option<&Node>
    }

    fn delete(&mut self, key: &String) -> Option<i32> {
        // extract code snippet
        let mut search_node = self.find(key);
        if search_node.is_some() {
            search_node.unwrap().node_map.remove(& 'x');
        }
        None
    }
}

Rust抱怨search_node.unwrap().chs部分下的错误:不能借用可变的"&"引用中的数据

所以我知道find函数返回Option<&Node>,所以在上一行展开时,我得到了对Node的引用。

尝试次数:

  • 我尝试通过以下方式取消引用该节点:*search_node.unwrap().node_map.remove(& 'x');*(search_node.unwrap()).node_map.remove(& 'x');,但是它仍然会引发错误。
  • 我在这里遵循了另一个答案,并尝试使node_map可变,例如:
1
2
3
4
 struct Node<'a> {
     node_map: &'a mut HashMap<char, Node<'a>>,
     value: Option<i32>,
 }

但是后来我抱怨说缺少几个地方。 我不知道如何添加的一个特定地方是new函数。

请让我知道如何解决原始问题或如何增加适当的寿命。


问题是find返回一个(可选的)不可变的引用,但是随后您尝试对其进行突变。 因此,您可能要添加带有签名的方法find_mut

1
fn find_mut(&mut self, key: &str) -> Option<&mut Node>

(我将key参数更改为&str,因为不建议将&String作为参数)

另一件风格上的事情:您应该使用if let而不是检查search_node是否存在然后再展开。

1
2
3
if let Some(search_node) = self.find_mut(key) {
    search_node.node_map.remove(&'x');
}