Line Filters in Rust
Here’s the translation of the Go line filter program to Rust, along with explanations in Markdown format suitable for Hugo:
A line filter is a common type of program that reads input on stdin, processes it, and then prints some derived result to stdout. grep and sed are common line filters.
Here’s an example line filter in Rust that writes a capitalized version of all input text. You can use this pattern to write your own Rust line filters.
use std::io::{self, BufRead, Write};
fn main() -> io::Result<()> {
    // Wrapping the unbuffered stdin with a buffered reader gives us a convenient
    // lines() method that returns an iterator over the lines of input.
    let stdin = io::stdin();
    let reader = stdin.lock();
    for line in reader.lines() {
        let line = line?;
        // Convert the line to uppercase
        let upper_case = line.to_uppercase();
        // Write out the uppercased line
        println!("{}", upper_case);
    }
    Ok(())
}To try out our line filter, first make a file with a few lowercase lines.
$ echo 'hello'   > /tmp/lines
$ echo 'filter' >> /tmp/linesThen use the line filter to get uppercase lines.
$ cat /tmp/lines | cargo run
HELLO
FILTERThis Rust program does the following:
We use the
std::iomodule for input/output operations.The
mainfunction returns aResultto handle potential I/O errors.We create a buffered reader from the standard input using
io::stdin().lock().We iterate over the lines of input using the
lines()method, which returns an iterator over the lines.For each line, we convert it to uppercase using the
to_uppercase()method.We print each uppercased line using
println!.Any I/O errors are propagated using the
?operator.
This Rust version achieves the same functionality as the original Go program, using idiomatic Rust constructs and error handling.