Cannot borrow data in a `&` reference as mutable for a Vec of HashSet

Hi Rust community,

after long hours of trying sort things out, I'm still not able to make following piece of code working:

#![allow(unused)]

use std::collections::HashSet;
fn main() {
    let mut rows: Vec<_> = (0..9).map(|_| HashSet::<u8>::new()).collect();
    rows.get(20).as_mut().unwrap().insert(5);
}

I want to have vector of 9 HashSets (for Sudoku solver) . I want to work on those HashSets, but I'm getting:

cannot borrow data in a & reference as mutable

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&code=%23![allow(unused)] use%20std%3A%3Acollections%3A%3AHashSet%3B fn%20main()%20{ %20%20%20%20let%20mut%20rows%3A%20Vec<_>%20%3D%20(0..81).map(|_|%20HashSet%3A%3A<u8>%3A%3Anew()).collect()%3B %20%20%20%20rows.get(20).as_mut().unwrap().insert(5)%3B }

I appreciate your help, Thanks

It probably helps to see what the types are:

rows.get(20) // Option<&HashSet<u8>>
    .as_mut() // Option<&mut &HashSet<u8>>
    .unwrap() // &mut &HashSet<u8>
    .insert(5);

However a mutable reference to an immutable reference only provides you with immutable access.

What you want here is to use get_mut instead.

4 Likes

Work like a charm! Thank you!!!

As long as you know that your indices are supposed to be in bounds, then there’s also the option of writing rows[20].insert(5).

This would panic if the index isn’t valid (very similar to how you’re currently using .unwrap() ).

4 Likes