实现说明
filter_map 一趟完成转换与丢弃可以归结为函数 main。
这个示例中仅有的重复出现在 for line in report 里。match 一条一条覆盖值的形态——不会意外落到默认分支上。
使用要点
- 跑完文件,输出里会留下标记——
readings:、mean:。
常见问题
运行「filter_map 一趟完成转换与丢弃」会打印什么?
运行文件本身,readings:、mean: 这些前缀各对应一段演示逻辑。
核心语句
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:?}")),
})
代码示例
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}");
}