← 中文资源

简体中文版本

take_while_inclusive 保留边界元素

take_while 在谓词首次失败时吞掉边界值,take_while_inclusive 把它也产出后才停止:告警、审计这类需要看到肇事样本的场景用它。

阅读英文原文

实现说明

take_while_inclusive 保留边界元素的核心是函数 main。

使用要点

  • 直接运行文件,输出会带上标签,比如 take_while:、inclusive:、hot first:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「take_while_inclusive 保留边界元素」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 take_while:、inclusive:、hot first: 这类标签。

核心语句

let readings = [21.5, 22.0, 88.1, 19.9, 20.2];
let with_boundary: Vec<f64> = readings
    .into_iter()
    .take_while_inclusive(|r| *r < 50.0)
    .collect();
let hot: Vec<f64> = [90.0, 20.0]
    .into_iter()
    .take_while_inclusive(|r| *r < 50.0)
    .collect();

代码示例

fn main() {
    let readings = [21.5, 22.0, 88.1, 19.9, 20.2];

    // take_while:首个超限样本被吃掉,边界值不可见
    let plain: Vec<f64> = readings
        .into_iter()
        .take_while(|r| *r < 50.0)
        .collect();
    println!("take_while: {plain:?}");

    // take_while_inclusive:超限的那条也产出,告警要带上肇事样本
    let with_boundary: Vec<f64> = readings
        .into_iter()
        .take_while_inclusive(|r| *r < 50.0)
        .collect();
    println!("inclusive: {with_boundary:?}");

    // 首个元素就超限:普通版得到空集,inclusive 仍返回那条
    let hot: Vec<f64> = [90.0, 20.0]
        .into_iter()
        .take_while_inclusive(|r| *r < 50.0)
        .collect();
    println!("hot first: {hot:?}");
}