Retain Mut Updates While Filtering

retain_mut hands each element a mutable reference: mutate first, then decide to keep or drop, finishing update and pruning in a single pass.

RustData Integrity

Code

rustsnippet
27 lines
#[derive(Debug)]
struct Job {
    name: &'static str,
    priority: u8,
}

fn main() {
    let mut queue = vec![
        Job { name: "index", priority: 2 },
        Job { name: "report", priority: 7 },
        Job { name: "cleanup", priority: 1 },
        Job { name: "notify", priority: 9 },
    ];

    // retain_mut:可变借用每个元素,先改再决定去留,一次遍历完成
    queue.retain_mut(|job| {
        if job.priority < 3 {
            job.priority += 5; // 提升优先级后保留
            return true;
        }
        job.priority <= 8 // 超过上限的直接淘汰
    });

    let kept: Vec<&str> = queue.iter().map(|job| job.name).collect();
    println!("kept: {kept:?}");
    println!("first: {:?}", queue.first());
}

How it works

Count the function main as the entire surface area of Retain Mut Updates While Filtering.

Using it

Running the file prints labeled results such as kept:, first: — each operation’s effect is visible in the output.

Key statements

let kept: Vec<&str> = queue.iter().map(|job| job.name).collect();
job.priority += 5; // 提升优先级后保留
return true;

Interactive Tools for This Topic

FAQ

What does Retain Mut Updates While Filtering print when run?
The script runs standalone; its 2 labeled outputs include `kept:`, `first:`.