← 中文资源

简体中文版本

用 then_some 与 then 构造 Option

then_some 立即求值、then 接闭包惰性构造:布尔判定直接变 Option,校验问题列表用 extend 一并收集,省掉两臂 match。

阅读英文原文

实现说明

全部逻辑都在函数 problems、main中。 for draft in &drafts 承担全部的逐项处理。

使用要点

  • 跑完文件,输出里会留下标记——ok: \、issues:、badge:。
  • 运行整个文件:main 会依次驱动 problems。

常见问题

运行「用 then_some 与 then 构造 Option」会打印什么?

整个文件跑完,输出行以 ok: \、issues:、badge: 这类前缀开头。

入口签名:fn problems(&self) -> Vec<String>

核心语句

problems.extend(over_budget.then(|| format!("{} words exceeds budget", self.word_count)));

代码示例

struct Draft {
    title: String,
    word_count: usize,
}

impl Draft {
    // validation rules: boolean verdicts become Options, and extend collects them into one issues list
    fn problems(&self) -> Vec<String> {
        let blank = self.title.trim().is_empty();
        let over_budget = self.word_count > 5000;

        let mut problems = Vec::new();
        problems.extend(blank.then_some("title is blank".to_string()));
        problems.extend(over_budget.then(|| format!("{} words exceeds budget", self.word_count)));
        problems
    }
}

fn main() {
    let drafts = [
        Draft { title: "  ".into(), word_count: 6000 },
        Draft { title: "release notes".into(), word_count: 420 },
    ];

    for draft in &drafts {
        let probs = draft.problems();
        if probs.is_empty() {
            println!("ok: \"{}\"", draft.title.trim());
        } else {
            println!("issues: {probs:?}");
        }
    }

    // then_some evaluates eagerly; then takes a closure, so an expensive construction runs only when true.
    // equivalent to match starred { true => Some("★"), false => None }
    let starred = true;
    println!("badge: {:?}", starred.then_some("★"));
}