← 中文资源

简体中文版本

find_map 找到第一个可解析值

find_map 把过滤与映射合并成一次遍历:候选项里第一个解析成功的就是答案,全部失败返回 None,调用方再决定默认值,溢出值同样被跳过。

阅读英文原文

实现说明

底层就是函数 first_port、main。 输入的每种形态各占一个 match 分支,编译器检查这套分支是否完整。

使用要点

  • 直接运行文件,输出会带上标签,比如 first usable port:、no usable port found、hopeless:——输出的每一行都能指回产生它的那次调用。
  • 运行整个文件:main 会依次驱动 first_port。

常见问题

运行「find_map 找到第一个可解析值」会打印什么?

运行文件本身,first usable port:、no usable port found、hopeless: 这些前缀各对应一段演示逻辑。

主要签名是 fn first_port(candidates: &[&str]) -> Option<u16>

核心语句

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"),
}

代码示例

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));
}