Command Line Arguments
Create the project and handle command line arguments:
$ cargo new minigrep
$ cd minigrep
Target usage: cargo run -- searchstring example-filename.txt
Reading Arguments
Use std::env::args
to access command line arguments:
use std::env; fn main() { let args: Vec<String> = env::args().collect(); dbg!(args); }
Key points:
env::args()
returns an iterator over argumentscollect()
converts the iterator toVec<String>
- First argument (
args[0]
) is always the binary name - Invalid Unicode in arguments will panic; use
env::args_os()
forOsString
if needed
Storing Arguments
Extract the required arguments into variables:
use std::env;
fn main() {
let args: Vec<String> = env::args().collect();
let query = &args[1];
let file_path = &args[2];
println!("Searching for {query}");
println!("In file {file_path}");
}
This basic implementation lacks error handling for insufficient arguments - we’ll address that in the refactoring section.