std-method

Vec::retain_mut

Visit each original element in order with mutable access, retaining those that pass the predicate. This can normalize values and remove rejected ones in one traversal. Expected stdout (not executed): [4, 6] Common mistake: Assuming changes to a rejected element keep that element in the vector.

Formal Syntax & Structure

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

Working Example

Example Snippetrust
fn main() {    let mut values = vec![1, 2, 3];    values.retain_mut(|n| { *n *= 2; *n >= 4 });    println!("{values:?}");}
Rust Reference