Filter Options With Option::filter And is_some_and
Narrow optional values with Option::filter and answer present-and-valid questions with is_some_and, both driven by a single predicate closure.
Code
fn validate(score: Option<i32>) -> Option<i32> {
// Option::filter:Some 且谓词通过才保留,None 原样穿透
score.filter(|s| (0..=100).contains(s))
}
fn main() {
let good = validate(Some(87));
let out_of_range = validate(Some(142));
let missing = validate(None);
println!("{:?} {:?} {:?}", good, out_of_range, missing);
// is_some_and:一步完成"存在且合法"判断,消费 Option 不留借用
let score = Some(87);
println!(
"present and valid: {}",
score.is_some_and(|s| (0..=100).contains(s))
);
let none: Option<i32> = None;
println!("none is valid: {}", none.is_some_and(|s| (0..=100).contains(s)));
// 与 map + unwrap_or 组合:非法值折叠为默认
let clamped = validate(Some(142)).map(|s| s / 2).unwrap_or(0);
println!("clamped: {clamped}");
}How the snippet works
Filter Options With Option::filter And is_some_and reduces to the functions validate and main.
Using it
The main signature reads fn validate(score: Option<i32>) -> Option<i32>
Running the file prints labeled results such as present and valid:, none is valid:, clamped: — each operation’s effect is visible in the output.
The demo flow inside main is validate — run the file to see it end to end.
Key statements
let clamped = validate(Some(142)).map(|s| s / 2).unwrap_or(0);
fn validate(score: Option<i32>) -> Option<i32> {
// Option::filter:Some 且谓词通过才保留,None 原样穿透
score.filter(|s| (0..=100).contains(s))
}
let out_of_range = validate(Some(142));
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- What does Filter Options With Option::filter And is_some_and print when run?
- Invoke the file as-is — the `present and valid:`, `none is valid:`, `clamped:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.