std-method

Vec::retain

Keep elements for which the predicate returns true, preserving their order. The predicate receives a shared reference and is called once per original element in order. Expected stdout (not executed): [3, 5] Common mistake: Returning true for the elements you intend to delete.

Formal Syntax & Structure

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

Working Example

Example Snippetrust
fn main() {    let mut readings = vec![3, -1, 5, 0];    readings.retain(|n| *n > 0);    println!("{readings:?}");}
Rust Reference