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.
Code
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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.