extract_if Removes And Yields
extract_if removes elements matching a predicate in place and yields them as an iterator, so pruning and collecting happen in one pass.
Code
// extract_if 按谓词取出元素:留下的留在 Vec,取走的变成迭代器
fn main() {
let mut queue: Vec<String> = vec![
"done:flush".into(),
"pending:a".into(),
"done:trim".into(),
"pending:b".into(),
];
// 谓词返回 true 的元素被移除并逐个产出
let completed: Vec<String> = queue
.extract_if(|task| task.starts_with("done:"))
.collect();
println!("extracted {} done tasks:", completed.len());
for task in &completed {
println!(" {task}");
}
println!("{} tasks remain in queue", queue.len());
for task in &queue {
println!(" {task}");
}
}How the snippet works
Under the hood: the function main.
for task in &completed is the one loop handling each item.
Caveats
- The import surface (if any) is all standard library, all versioned with the language itself.
Applying it
Headline declaration: fn main()
The demo output is labeled (extracted), with each printed line telling you which step made it.
Load-bearing statements
.extract_if(|task| task.starts_with("done:"))
.collect();
Interactive Tools for This Topic
FAQ
- What does extract_if Removes And Yields print when run?
- Run it as a complete program — the output lines carry labels such as `extracted`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.