简体   繁体   English

HashMap 出现结构错误:不能将“&”引用中的数据借用为可变

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

I have the following code:我有以下代码:

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 complains the error under search_node.unwrap().chs part: cannot borrow data in a "&" reference as mutable Rust 抱怨search_node.unwrap().chs部分下的错误:不能将“&”引用中的数据借用为可变

So I understand that the find function returns Option<&Node> so when unwrapping at the above line, I get the reference to Node .所以我知道find function 返回Option<&Node>所以当在上面的行展开时,我得到了对Node的引用。

Attempts :尝试

  • I tried to dereference the node by: *search_node.unwrap().node_map.remove(& 'x');我试图通过以下方式取消对节点的引用: *search_node.unwrap().node_map.remove(& 'x'); or *(search_node.unwrap()).node_map.remove(& 'x');*(search_node.unwrap()).node_map.remove(& 'x'); but it still throws error.但它仍然会引发错误。
  • I followed another answer here and tried to make node_map mutable like:在这里遵循了另一个答案,并尝试使node_map可变,例如:
 struct Node<'a> {
     node_map: &'a mut HashMap<char, Node<'a>>,
     value: Option<i32>,
 }

But then I got complain about lacking lifetime several places.但后来我抱怨缺乏生命的几个地方。 One particular place I dont know how to add is in the new function.我不知道如何添加的一个特殊地方是new的 function。

Please let me know how to solve the original issue or how to add the appropriate lifetime.请让我知道如何解决原始问题或如何添加适当的生命周期。

The problem is that find returns an (optional) immutable reference, but then you try to mutate it later.问题是find返回一个(可选的)不可变引用,但是您稍后会尝试对其进行变异。 For that reason, you'll probably want to add a method find_mut with signature出于这个原因,您可能需要添加一个带有签名的方法find_mut

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

(I changed the key argument to &str because it's discouraged to take &String as an argument ) (我将key参数更改为&str因为不鼓励将&String作为参数

Another stylistic thing: you should use if let instead of checking that search_node is some and then unwrapping.另一个风格的事情:你应该使用if let而不是检查search_node是一些然后展开。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM