How to Build a CLI Application in Rust

Cli
Build a Rust CLI app by initializing a Cargo project, parsing arguments into a Config struct, and implementing a run function to handle file I/O and errors.

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.

  1. Initialize the project and create the source file. cargo new minigrep && cd minigrep
  2. Add the standard library imports and define the Config struct in src/main.rs. use std::env; use std::error::Error; use std::fs; use std::process; struct Config { query: String, file_path: String }
  3. Implement the build method to parse command-line arguments into a Config instance. 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 }) } }
  4. Implement the run function to read the file and handle errors using Result. fn run(config: Config) -> Result<(), Box<dyn Error>> { let contents = fs::read_to_string(config.file_path)?; println!("With text:\n{contents}"); Ok(()) }
  5. Write the main function 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); } }
  6. Build and run the application with a query string and a file path. cargo run -- "search term" path/to/file.txt