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().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>, } |
但是后来我抱怨说缺少几个地方。 我不知道如何添加的一个特定地方是
请让我知道如何解决原始问题或如何增加适当的寿命。
问题是
1 | fn find_mut(&mut self, key: &str) -> Option<&mut Node> |
(我将
另一件风格上的事情:您应该使用
1 2 3 | if let Some(search_node) = self.find_mut(key) { search_node.node_map.remove(&'x'); } |