Take Options Conditionally With take_if
Evict a queued value only when a predicate holds with Option::take_if — the slot clears in place when it fires and stays untouched when it does not.
Code
#[derive(Debug)]
struct RetrySlot {
job: &'static str,
attempts: u32,
}
fn main() {
let mut slot = Some(RetrySlot { job: "sync", attempts: 3 });
// take_if: takes the value only when the predicate holds; otherwise it stays put, with no two-step if let
let evicted = slot.take_if(|s| s.attempts >= 3);
println!("evicted: {evicted:?}");
println!("slot now: {slot:?}");
// predicate false: the value stays where it was
slot = Some(RetrySlot { job: "index", attempts: 1 });
slot.take_if(|s| s.attempts >= 3);
println!("kept: {slot:?}");
// take_if on an empty slot likewise returns None
let mut pending: Option<u32> = None;
let nothing = pending.take_if(|v| *v > 0);
println!("from empty: {nothing:?}");
}How it works
Take Options Conditionally With take_if is built around the function main.
Putting it to use
Running the file prints labeled results such as evicted:, slot now:, kept: — each operation’s effect is visible in the output.
Core lines
let mut slot = Some(RetrySlot { job: "sync", attempts: 3 });
slot = Some(RetrySlot { job: "index", attempts: 1 });
let mut pending: Option<u32> = None;
Interactive Tools for This Topic
FAQ
- What does Take Options Conditionally With take_if print when run?
- No setup needed: run the file and look for labeled lines like `evicted:`, `slot now:`, `kept:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.