I have a HashMap
. Sender
is a open connection object and the key is a user id. Each user can connect from multiple devices. I ne
To do this with a HashMap
you should use a Vec
as the values, so that each key can point to multiple Sender
s. The type then would be HashMap<u32, Vec<Sender>>
.
Using this structure, just using insert()
can get clunky when you need to mutate the values like this, but instead you can use the Entry
API for retrieving and updating records in one go. For example:
let mut hash_map: HashMap<u32, Vec<Sender>> = HashMap::new();
hash_map.entry(3)
// If there's no entry for key 3, create a new Vec and return a mutable ref to it
.or_default()
// and insert the item onto the Vec
.push(sender);
You could also use the multimap crate, which does something similar under the hood, but adds a layer of abstraction. You might find it easier to work with:
let mut multi_map = MultiMap::new();
multi_map.insert(3, sender_1);
multi_map.insert(3, sender_2);
The method multi_map.get(key)
will the first value with that key, while multi_map.get_vec(key)
will retrieve all of them.