如何在 Rust 中一次读取和处理文件的 N 行?

mlb*_*ght 3 io rust

我想一次读取一个文件的 N 行,可能使用itertools::Itertools::chunks.

当我做:

for line in stdin.lock().lines() {
   ... // this is processing one line at a time
}
Run Code Online (Sandbox Code Playgroud)

...虽然我正在缓冲输入,但我没有处理缓冲区。

Sta*_*eur 5

您可以使用chunks()itertools:

use itertools::Itertools; // 0.8.0
use std::io::BufRead;

fn main() {
    let stdin = std::io::stdin();
    let n = 3;

    for lines in &stdin.lock().lines().chunks(n) {
        for (i, line) in lines.enumerate() {
            println!("Line {}: {:?}", i, line);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)