← 中文资源

简体中文版本

用 take_if 条件取走 Option

用 Option::take_if 按谓词取走槽位值:条件成立就地清空并拿到 Some,不成立原样保留,省掉 if let 的两步走。

阅读英文原文

实现说明

用 take_if 条件取走 Option可以归结为函数 main。

使用要点

  • 演示输出是带标签的(evicted:、slot now:、kept:),每个操作都会留下自己的一行标注。

常见问题

运行「用 take_if 条件取走 Option」会打印什么?

运行文件本身,evicted:、slot now:、kept: 这些前缀各对应一段演示逻辑。

核心语句

let mut slot = Some(RetrySlot { job: "sync", attempts: 3 });
slot = Some(RetrySlot { job: "index", attempts: 1 });
let mut pending: Option<u32> = None;

代码示例

#[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:?}");
}