How to use the same iterator twice, once for counting and once for iteration?

后端 未结 3 1177
悲哀的现实
悲哀的现实 2021-01-12 07:47

It seems that an iterator is consumed when counting. How can I use the same iterator for counting and then iterate on it?

I\'m trying to count the lines in a file an

3条回答
  •  长情又很酷
    2021-01-12 08:28

    The other answers have already well-explained that you can either recreate your iterator or clone it.

    If the act of iteration is overly expensive or it's impossible to do multiple times (such as reading from a network socket), an alternative solution is to create a collection of the iterator's values that will allow you to get the length and the values.

    This does require storing every value from the iterator; there's no such thing as a free lunch!

    use std::fs;
    
    fn main() {
        let log_content = fs::read_to_string("/home/myuser/test.log").unwrap();
        let lines: Vec<_> = log_content.lines().collect();
    
        println!("{} lines", lines.len());
        for value in lines {
            println!("{}", value);
        }
    }
    

提交回复
热议问题