Chaining and iterators over I/O
In this section, we'll look at how to use iterators and chaining with the std::io
module.
Many of the data structures provided by the std::io
module have built-in iterators. Iterators let you process a series of items, such as lines in a file or incoming network connections on a port. They provide a nicer mechanism compared to while
and for
loops. Here is an example of using the lines()
iterator with the BufReader
struct, which is a part of the std::io
module. This program reads lines from the standard input stream in a loop:
use std::io::{BufRead, BufReader}; fn main() { // Create handle to standard input let s = std::io::stdin(); //Create a BufReader instance to optimize sys calls let file_reader = BufReader::new(s); // Read from standard input line-by-line for single_line in file_reader.lines(...