Can't borrow mutable/immutable with println! and HashMap-learning The Book

Hi I'm going the hash maps part of The Book and keep hitting my head up against a wall trying to get around the 'cannot borrow as mutable because it is also borrowed as immutable'. I tried to create scope for the immutable moves, I can't see what the score variable is with either rust println! or dbg!

I also tried to create the variable at the top of my scope by going through the compiler errors still to no avail. Can someone help me see where I'm going wrong?

    fn main() {
        use std::collections::HashMap;

        let mut scores = HashMap::new();
        //let mut score: Option<String> = Some(" ".to_string());
        //let mut score: Option<&i32> = Some(&10);
        {
            scores.insert(String::from("Blue"), 10);
            scores.insert(String::from("Yellow"), 50);
            for (key, value) in &scores {
                println!("{}: {}", key, value);
            }
        }
        let team_name = String::from("Blue");
        let score = scores.get(&team_name);
        {
            scores.insert(String::from("Blue"), 25);
            scores.entry(String::from("Blue")).or_insert(45);
            scores.entry(String::from("Yellow")).or_insert(12);
            scores.entry(String::from("Red")).or_insert(52);
        }

        println!("{:?}", &score);
        println!("{:?}", &scores);
    }
1 Like

scores.get() returns an Option<&{integer}>. So, it's an Option of a reference to an integer within the hashmap. So as long as that Option exists, it might contain a reference to something (the number) within the hashmap. The subsequent insert operation however mutate the hashmap, and might relocate the number you still have a reference to, so that's not allowed. Solution is to copy the value out if there is a value, and otherwise keep the none. After that, you have no more reference pointing into the hashmap. That also means that blue's final score will be Some(10).

solution: Rust Playground

2 Likes

OK! That makes much more sense, thanks. This is my first question here and the community is just an helpful and kind as your reputation. Much appreciated.

2 Likes