Build Options With then_some And then

Replace two-arm true-or-None matches with then_some for eager values and then for lazy closures, and extend validation lists straight from the results.

RustForm Validation

Code

rustsnippet
38 lines
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("★"));
}

How the snippet works

Build Options With then_some And then keeps everything in the functions problems and main.

Repetition is confined to for draft in &drafts — the rest of the file is straight-line.

Applying it

The main signature reads fn problems(&self) -> Vec<String>

Running the file prints labeled results such as ok: \, issues:, badge: — each operation’s effect is visible in the output.

There are 1 call inside main — problems — executed top to bottom.

Statements that matter

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
}

Interactive Tools for This Topic

FAQ

What does Build Options With then_some And then print when run?
Invoke the file as-is — the `ok: \`, `issues:`, `badge:` prefixes identify which step printed each line.