Create a new binary crate with Cargo, define a Config struct to parse arguments, and implement a run function that reads a file and processes its contents.
- Initialize the project and create the source file.
cargo new minigrep && cd minigrep - Add the standard library imports and define the
Configstruct insrc/main.rs.use std::env; use std::error::Error; use std::fs; use std::process; struct Config { query: String, file_path: String } - Implement the
buildmethod to parse command-line arguments into aConfiginstance.impl Config { fn build(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments"); } let query = args[1].clone(); let file_path = args[2].clone(); Ok(Config { query, file_path }) } } - Implement the
runfunction to read the file and handle errors usingResult.fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; println!("With text:\n{contents}"); Ok(()) } - Write the
mainfunction to collect arguments, build the config, and execute the run logic.fn main() { let args: Vec<String> = env::args().collect(); let config = Config::build(&args).unwrap_or_else(|err| { println!("Problem parsing arguments: {err}"); process::exit(1); }); if let Err(e) = run(config) { println!("Application error: {e}"); process::exit(1); } } - Build and run the application with a query string and a file path.
cargo run -- "search term" path/to/file.txt