std-method
BTreeSet::retain
Keep only elements accepted by the predicate. Elements are visited in ascending order; they cannot be mutated through the predicate. Expected stdout (not executed): [2, 4] Common mistake: Trying to mutate elements so their ordering changes.
Formal Syntax & Structure
rust syntaxrust
fn retain<F>(&mut self, f: F) where F: FnMut(&T) -> boolWorking Example
Example Snippetrust
fn main() { use std::collections::BTreeSet; let mut ids = BTreeSet::from([1, 2, 3, 4]); ids.retain(|n| n % 2 == 0); println!("{:?}", ids.into_iter().collect::<Vec<_>>());}