filter_map Drops And Transforms In One Pass
filter_map converts and discards in a single pass: parse failures collapse to None and vanish, successful parses flow on as Some values.
Code
fn main() {
// Raw event stream: sensor readings carrying dirty data
let raw = ["21.5", "", "19.8", "error", "23.1"];
// filter_map drops and converts in a single pass:
// elements that fail to parse (empty/non-numeric) fold into None and vanish; successes yield f32
let readings: Vec<f32> = raw
.iter()
.filter_map(|cell| cell.parse::<f32>().ok())
.collect();
println!("readings: {:?}", readings);
// To keep the drop reason, model it explicitly with match - still one pass
let report: Vec<String> = raw
.iter()
.filter_map(|cell| match cell.parse::<f32>() {
Ok(value) => Some(format!("ok {value}")),
Err(_) => Some(format!("dropped {cell:?}")),
})
.collect();
for line in report {
println!("{line}");
}
// Downstream stats rest on valid readings only
let mean = readings.iter().sum::<f32>() / readings.len() as f32;
println!("mean: {mean}");
}Inside the snippet
filter_map Drops And Transforms In One Pass is built around the function main.
Repetition is confined to for line in report — the rest of the file is straight-line. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.
Putting it to use
Running the file prints labeled results such as readings:, mean: — each operation’s effect is visible in the output.
Core lines
let mean = readings.iter().sum::<f32>() / readings.len() as f32;
.filter_map(|cell| match cell.parse::<f32>() {
Ok(value) => Some(format!("ok {value}")),
Err(_) => Some(format!("dropped {cell:?}")),
})
Interactive Tools for This Topic
FAQ
- What does filter_map Drops And Transforms In One Pass print when run?
- Execute the whole file; each printed line is prefixed with a label like `readings:`, `mean:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.