实现说明
全部逻辑都在函数 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("★"));
}