A small command line search tool in Rust. Give it a query and a file, and it prints every line containing that query.
This is a learning project following Chapter 12 of The Rust Programming Language, with one deliberate change from the book version described below.
cargo run -- <query> <file_path>Case sensitive search:
$ cargo run -- duct poem.txt
safe, fast, productive.Case insensitive search, enabled by setting the IGNORE_CASE environment variable to anything:
$ IGNORE_CASE=1 cargo run -- rUst poem.txt
Rust:
Trust me.On Windows PowerShell:
$Env:IGNORE_CASE=1; cargo run -- rUst poem.txtThe book's version of Config owns its data:
pub struct Config {
query: String,
file_path: String,
}It calls .clone() on both arguments, and the book is upfront that this is done to avoid lifetimes while the reader is still learning them.
This version borrows instead:
pub struct Config<'a> {
query: &'a str,
file_path: &'a str,
pub ignore_case: bool,
}The lifetime parameter tells the compiler that a Config cannot outlive the args vector it borrows from. In main, args lives for the whole function, so the borrow is valid. No allocation, no copying, and the compiler proves the references stay valid rather than relying on the programmer to check.
That is the whole point of the exercise for me. The clone version works fine and nobody would notice the difference at this scale. Writing the borrowed version is what forced me to actually understand what a lifetime annotation is claiming.
src/
main.rs argument parsing, error handling, exit codes
lib.rs Config, run, the two search functions, tests
Splitting the logic into lib.rs is what makes the search functions testable. main.rs keeps only the parts that are awkward to test: reading env::args, printing to stderr, and calling process::exit.
Errors are separated by kind. Argument problems are caught by Config::build and reported before any work starts. Runtime problems, like a missing file, come back from run as Box<dyn Error>. Both print to stderr with eprintln! and exit with status 1, so the output can be piped without error messages polluting the results.
cargo testTwo tests cover the case sensitive and case insensitive search paths.
- Search is a plain substring match, not a regular expression
- Reads the entire file into memory with
read_to_string, so it is unsuited to very large files - Case insensitivity is controlled only by the environment variable, not a command line flag
- Only one file at a time, no directory or recursive search
- Matched lines are trimmed of surrounding whitespace before printing, so output does not preserve the original indentation