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.

RustForm Validation

Code

rustsnippet
24 lines
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

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.