std-method

BTreeMap::retain

Keep records whose predicate returns true. The predicate may inspect keys and update values, and visits records in ascending key order. Expected stdout (not executed): [2, 3] Common mistake: Returning true for items you intend to delete.

Formal Syntax & Structure

rust syntaxrust
fn retain<F>(&mut self, f: F) where F: FnMut(&K, &mut V) -> bool

Working Example

Example Snippetrust
fn main() {    use std::collections::BTreeMap;    let mut stock = BTreeMap::from([(1, 0), (2, 4), (3, 1)]);    stock.retain(|_, count| *count > 0);    println!("{:?}", stock.keys().collect::<Vec<_>>());}
Rust Reference