Rust:如何过滤掉“无”排放?

bru*_*olf 7 iterator rust

我的用例是我想扫描迭代器,并在原始迭代器的段上生成累积值(这是用于标记器)。换句话说,输入值和输出值之间不是一对一的映射。请注意,这filter_map()不起作用,因为我确实需要累加器值。

我发现.scan(),这几乎就是我想要的:

#![allow(unused)]
fn main() {
    let a = [1, 2, 3];
    
    let mut iter = a.iter().scan(1, |state, &x| {
        if x == 2 {
            return None;
        }
    
        // each iteration, we'll multiply the state by the element
        *state = *state * x;
    
        // then, we'll yield the negation of the state
        Some(-*state)
    });
    
    println!("{:?}", &iter.next());
    println!("{:?}", &iter.next());
    println!("{:?}", &iter.next());
}
Run Code Online (Sandbox Code Playgroud)

除了上面的输出

Some(-1)
None
Some(-3)
Run Code Online (Sandbox Code Playgroud)

当我想要它输出时

Some(-1)
Some(-3)
None
Run Code Online (Sandbox Code Playgroud)

而且,不管你怎么想,这都行不通:

Some(-1)
None
Some(-3)
Run Code Online (Sandbox Code Playgroud)

因为我实际上并没有迭代Options:

error[E0599]: no method named `is_some` found for reference `&{integer}` in the current scope
  --> src/main.rs:15:21
   |
15 |     }).filter(|x| x.is_some());
   |                     ^^^^^^^ method not found in `&{integer}`
Run Code Online (Sandbox Code Playgroud)

所以这就像迭代器方法被故意屏蔽“丢失产量值”的情况。

我有什么想法可以a)过滤掉那些缺失的产量,或者b)以某种完全不同的方式完成上述任务?

Cod*_*256 8

filter_map您可以在迭代器外部的变量中使用并创建自己的累加器:

fn main() {
    let a = [1, 2, 3];

    let mut state = 1;

    let mut iter = a.iter().filter_map(|&x| {
        if x == 2 {
            return None;
        }

        // each iteration, we'll multiply the state by the element
        state = state * x;

        // then, we'll yield the negation of the state
        Some(-state)
    });

    println!("{:?}", &iter.next()); // Some(-1)
    println!("{:?}", &iter.next()); // Some(-3)
    println!("{:?}", &iter.next()); // None
}
Run Code Online (Sandbox Code Playgroud)