Hashmap lacks of get_mut API
xuchaoqian opened this issue · comments
Chaoqian Xu commented
The current design of hashmap API doesn't support nested structures well.
For example:
pub struct ConnectionPool {
slots: FlurryHashMap<String, ConnectionSlot>,
}
pub struct ConnectionSlot {
endpoint: String,
connections: Vec<Connection>,
}
pub fn remove<S: AsRef>(&self, endpoint: S, connection: &Connection)
let guard = self.slots.guard();
self.slots.get(endpoint.as_ref(), &guard).map(|slot| {
slot.remove(connection); // cannot borrow `*slot` as mutable, as it is behind a `&` reference
});
}
Jon Gjengset commented
It is unfortunately not possible to provide a get_mut
interface to a concurrent hash-map like this without locks, because you need a mechanism for excluding other read operations while the get_mut
borrow is active. Instead, with a concurrent map, you'll want to use a function like HashMap::compute_if_present
, which lets you do something kind of like this. Otherwise, consider a lock-based concurrent map like dashmap
, which does have get_mut
.