Take _any_ element from HashMap: Option<(K, V)>

Is there an idiomatic way to take any value from a HashMap (I don't care which one). None if HashMap is empty.

This function would have type signature &mut self -> Option<(K, V)>. I searched HashMap in std::collections - Rust but found pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)> which requires a key.

Context: I'm using a HashMap to represent a set of named consumers; and when something is ready, I want to send it to some consumer, I don't care which one.

If your key can be cheaply cloned, you could call keys().next(), then clone and remove it.

Do you still need the map to be otherwise usable as a normal map when you're in this phase? If you're allowed to fully consume it, then you can just keep its IntoIter and pick off items one by one.

1 Like

I forgot to state: I also need to be able to add to this HashMap as well; so the ops are :

  • add new named consumer
  • remove some consumer (don't care which key)
  • remove particular consumer (by key)

If it doesn't have to be HashMap exactly, then you could use IndexMap and its pop() method. You can also use swap_remove_index on a randomly chosen index in 0..len(), if you don't want to be biased toward the last insertion.


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.