I followed the code in question How do I handle/circumvent "Cannot assign to ... which is behind a & reference" in Rust? but I am still unable to follow how to implement the same suggestion in my code and I get the same error.
I am trying to add a HashMap to the next
of the node (head of thee WordDictionary) and then insert a new entry into it.
use std::collections::HashMap;
#[derive(Debug)]
struct Node {
word: String,
next: Option<HashMap<i32, Node>>,
}
impl Node {
fn new(word: String) -> Self {
Node {
word,
next: None,
}
}
}
#[derive(Debug)]
struct WordDictionary {
head: Option<Node>,
}
impl WordDictionary {
fn new() -> Self {
WordDictionary {
head: None,
}
}
fn add_word(&mut self, word: String) {
if word.len() == 0 {
return;
}
match &self.head {
None => {
self.head = Some(Node::new("".to_string()));
self.head.as_ref().unwrap().next = Some(HashMap::new()); // <-- Throws error
// insert the value then.
return
}
Some(_) => { /* Do something */ }
}
}
}
fn main() {
{
let mut wordDictionary = WordDictionary::new();
wordDictionary.add_word("bad".to_string());
}
}
I get the same error:
Compiling playground v0.0.1 (/playground)
error[E0594]: cannot assign to data in a `&` reference
--> src/main.rs:38:17
|
38 | self.head.as_ref().unwrap().next = Some(HashMap::new());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot assign
For more information about this error, try `rustc --explain E0594`.
error: could not compile `playground` due to previous error
It would be great if someone could help me with what is the right way to implement this assignment and insert an entry to the map.
Thank you!