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
So I understand that the find
function returns Option<&Node>
so when unwrapping at the above line, I get the reference to Node
.
Attempts:
- I tried to dereference the node by:
*search_node.unwrap().node_map.remove(& 'x');
or*(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:
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.
Please let me know how to solve the original issue or how to add the appropriate lifetime.