Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Command line arguments - args

  • std::env
  • args
  • Vec

At first the code to accept command line parameters might look scary and thus at this point we won't go into the details. However it is nice to be able to accept parameters from the command line to add some interaction to the code. So for now let's just accept the code.

fn main() {
    let args = std::env::args().collect::<Vec<String>>();
    println!("{args:?}");

    if args.len() < 2 {
        eprintln!("Usage: {} param", args[0]);
        std::process::exit(1);
    }
    let param = &args[1];
    println!("{param:?}");

    let number = param.parse::<u32>().expect("We expected a number");
    println!("{number}");
    println!("{}", number + 1);
}