代码之家  ›  专栏  ›  技术社区  ›  yegor256

如何在Rust中查找并计数?

  •  1
  • yegor256  · 技术社区  · 3 年前

    我试图通过迭代器,选择某些元素,对它们中的每一个做一些事情,然后计算它们中有多少受到了影响:

    let done = foo
      .into_iter()
      .filter(...)
      .for_each(|i| do_something_with(i))
      .len();
    

    从那以后就不起作用了 for_each 不返回迭代器。到目前为止,我发现最好的选择是:

    let mut done = 0;
    foo
      .into_iter()
      .filter(...)
      .for_each(|i| { do_something_with(i); done += 1; });
    

    也许还有一个更优雅的永恒的?

    1 回复  |  直到 3 年前
        1
  •  5
  •   Peng Guanwen    3 年前

    如果您想对每个元素执行某些操作,但不消耗元素的所有权,那么 Iterator::inspect 是要使用的方法。

    代码中的另一个问题是 Iterator::count 应该使用而不是 ExactSizeIterator::len .

    示例代码:

    use core::fmt::Debug;
    
    fn do_something_with(i: impl Debug) {
        println!("{:?}", i);
    }
    
    fn main() {
        let foo = [1, 2, 3];
        let done: usize = foo
            .into_iter()
            .filter(|x| x % 2 == 1)
            .inspect(|i| do_something_with(i))
            .count();
        
        println!("{done}");
    }
    
    推荐文章