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 - print all args

  • std::env

  • args

  • Vec

  • We load the std::env module

  • #[allow(clippy::needless_range_loop)] is needed to silence clippy, the linter

use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();
    println!("My path is {}", args[0]);
    println!("Number of arguments is {}", args.len());

    #[allow(clippy::needless_range_loop)]
    for i in 1..args.len() {
        println!("Parameter {} is '{}'", i, args[i]);
    }
}
cargo run

My path is target/debug/args
Number of arguments is 1
cargo run apple banana

My path is target/debug/args
Number of arguments is 3
Parameter 1 is 'apple'
Parameter 2 is 'banana'