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/lines

Then use the line filter to get uppercase lines.

$ cat /tmp/lines | cargo run
HELLO
FILTER

This Rust program does the following:

  1. We use the std::io module for input/output operations.

  2. The main function returns a Result to handle potential I/O errors.

  3. We create a buffered reader from the standard input using io::stdin().lock().

  4. We iterate over the lines of input using the lines() method, which returns an iterator over the lines.

  5. For each line, we convert it to uppercase using the to_uppercase() method.

  6. We print each uppercased line using println!.

  7. 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.