'Multiple Immutable References

I have the following code:

use std::collections::HashMap;

fn doublez(h1: &HashMap<String, i32>, h2: &HashMap<String, i32>) {
    dbg!(h1, h2);
}

fn main() {
    let mut scores = HashMap::new();

    scores.insert(String::from("Blue"), 10);
    scores.insert(String::from("Yellow"), 50);

    let teams = vec![
        String::from("Blue"),
        String::from("Yellow"),
    ];

    let initial_scores = vec![10, 50];
    let team_scores: HashMap<_, _> = teams.into_iter().zip(initial_scores.into_iter()).collect();
    let mut ts2 = &team_scores;
    let mut ts3 = &team_scores;
    doublez(ts2, ts3);
}

I'm experimenting with Rusts ownership rules and I was testing out the whole idea that you can't have multiple mutable references, but here in this code, I make two mutable references to the team_scores hashmap in the form of ts2 and ts3 but for whatever reason the code compiles just fine. Why is that?



Solution 1:[1]

let mut ts2 = &team_scores is not actually creating a mutable reference, but rather a mutable variable containing an immutable reference. This means you can reassign the variable to another reference (i.e. ts2 = &different_hashmap), but you won't be able to modify the HashMap itself (i.e. trying to call ts2.insert will not work).

If you want a mutable reference to the HashMap, you would use let ts2 = &mut team_scores;.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MattTheNub