1

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());
    }
}

Playground

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!

Coder
  • 1,415
  • 2
  • 23
  • 49
  • 1
    Change `as_ref()` to `as_mut()` and it compiles. – user4815162342 Jan 08 '22 at 22:49
  • Thanks! The rust compiler is actually misleading here (as it seems). – Coder Jan 08 '22 at 22:55
  • 1
    I wouldn't call it misleading; after all, `as_ref()` does return a `&` reference. Since the compiler has no special knowledge of `AsRef` and `AsMut` traits, it cannot guess that you wanted to call `as_mut()`, so it can only state the obvious (that you can't assign to a `&` reference). – user4815162342 Jan 08 '22 at 22:58

1 Answers1

2

Thanks to @user4815162342. As suggested, changing to as_mut() helped.

Here is the updated code on Playground

Coder
  • 1,415
  • 2
  • 23
  • 49