计数时似乎消耗了迭代器.如何使用同一个迭代器进行计数,然后对其进行迭代?
我试图数一数文件中的行数,然后打印出来.我能够读取文件内容,能够计算行数,但是我不再能够像内部光标位于迭代器末尾那样迭代这些行.
use std::fs::File;
use std::io::prelude::*;
fn main() {
let log_file_name = "/home/myuser/test.log";
let mut log_file = File::open(log_file_name).unwrap();
let mut log_content: String = String::from("");
//Reads the log file.
log_file.read_to_string(&mut log_content).unwrap();
//Gets all the lines in a Lines struct.
let mut lines = log_content.lines();
//Uses by_ref() in order to not take ownership
let count = lines.by_ref().count();
println!("{} lines", count); //Prints the count
//Doesn't enter in the loop
for value in lines {
println!("{}", value);
}
}
Iterator
没有reset
方法,但内部游标似乎位于计数后迭代器的末尾.是否必须通过再次调用log_content.lines()
来创建新的Lines
,或者我可以重置内部光标?
目前,我找到的解决方法是创建一个新的迭代器:
use std::fs::File;
use std::io::prelude::*;
fn main() {
let log_file_name = "/home/myuser/test.log";
let mut log_file = File::open(log_file_name).unwrap();
let mut log_content: String = String::from("");
//Reads the log file.
log_file.read_to_string(&mut log_content).unwrap();
//Counts all and consume the iterator
let count = log_content.lines().count();
println!("{} lines", count);
//Creates a pretty new iterator
let lines = log_content.lines();
for value in lines {
println!("{}", value);
}
}