Best way to implement a vector of mutable hashmaps

I was trying to build a vector of mutable hashsets, where the vector could be immutable. I used the interior mutability pattern to implement this (playground link).

let  v: Vec<RefCell<HashSet<i64>>> =(0 .. 10)
                        .map(|_| RefCell::new(HashSet::new()))
                        .collect();

Is there a better way to do this?

Besides, HashSet -> HashMap, I think Vec<RefCell<HashMap>> is exactly what you want.

1 Like

use vec! macro instead

let  v: Vec<RefCell<HashSet<i64>>> =vec![RefCell::new(HashSet::new());10];
1 Like

What do you mean exactly? If you want to store it behind an Rc, so you can't get a &mut, you might want that. Or maybe you want a Box<[HashSet<_>]> or a fixed length array.

As it is, the Vec in your example can still be mutated by moving it to a mut binding.

2 Likes

I want to maintain a vec of HashSets. I want to add/remove elements from the sets, but dont want add/remove any of the sets from the vec

Once you have a &mut Set you can add/remove it simultaneously via std::mem::swap

1 Like

At least with what's been shared so far, a fixed width array matches that goal the closest. Or perhaps a newtype that doesn't provide an API for changing the length (number of sets), which can also only be created with the desired length.


Swapping out a HashSet isn't really more powerful than removing all entries and adding new ones. But if you can get a &mut Box<[_]> or &mut VecWrapper (which can be created with different lengths), you can similarly swap it out, replacing it with one having a different length.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.