std-method
HashMap::retain
Keep records that satisfy a predicate; the predicate can inspect the key and change the value. Removed entries are dropped. The predicate must not depend on traversal order. Expected stdout (not executed): 2 false Common mistake: Trying to remove keys from the map separately inside retain.
Formal Syntax & Structure
rust syntaxrust
pub fn retain<F: FnMut(&K, &mut V) -> bool>(&mut self, f: F)Working Example
Example Snippetrust
fn main() { use std::collections::HashMap; let mut m = HashMap::from([("a", 2), ("b", 0), ("c", 4)]); m.retain(|_, v| *v > 0); println!("{} {}", m.len(), m.contains_key("b"));}