HashMap中的Struct错误:不能借用“&”引用中的数据作为可变项

问题描述 投票:0回答:1

我有以下代码:

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');来取消引用该节点,但仍会引发错误。
  • 我遵循了另一个答案here,并试图使node_map可变为:
 struct Node<'a> {
     node_map: &'a mut HashMap<char, Node<'a>>,
     value: Option<i32>,
 }

但是后来我抱怨缺少一生。我不知道如何添加的一个特定位置是new函数。

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

rust
1个回答
0
投票

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

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

(我将key参数更改为&str,因为it's discouraged to take &String as an argument

另一种风格:您应该使用&String而不是先检查if let是否存在然后解开。

search_node
© www.soinside.com 2019 - 2024. All rights reserved.