Find Map Returns First Parseable Value

find_map merges filtering and mapping into one pass, yielding the first item whose parse succeeds as Some and None when every candidate fails.

RustConfig Management

Code

rustsnippet
17 lines
fn first_port(candidates: &[&str]) -> Option<u16> {
    // find_map:过滤与映射一次完成,返回第一个解析成功的项
    candidates.iter().find_map(|c| c.parse::<u16>().ok())
}

fn main() {
    let env = ["", "not-a-port", "8443", "99999"];

    match first_port(&env) {
        Some(port) => println!("first usable port: {port}"),
        None => println!("no usable port found"),
    }

    // 全部失败返回 None:"99999" 溢出 u16 同样被跳过
    let hopeless = ["x", "99999"];
    println!("hopeless: {:?}", first_port(&hopeless));
}

What the code does

Find Map Returns First Parseable Value reduces to the functions first_port and main.

A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

Applying it

The primary signature is fn first_port(candidates: &[&str]) -> Option<u16>

The demo output is labeled (first usable port:, no usable port found, hopeless:), so every printed line maps back to its originating operation.

Treat main as the orchestrator calling first_port in a fixed order.

Statements that matter

fn first_port(candidates: &[&str]) -> Option<u16> {
// find_map:过滤与映射一次完成,返回第一个解析成功的项
candidates.iter().find_map(|c| c.parse::<u16>().ok())
}
match first_port(&env) {
Some(port) => println!("first usable port: {port}"),
None => println!("no usable port found"),
}

Interactive Tools for This Topic

FAQ

What does Find Map Returns First Parseable Value print when run?
Invoke the file as-is — the `first usable port:`, `no usable port found`, `hopeless:` prefixes identify which step printed each line.