RRust By Example
beginnerCLI

Command Line Arguments

Parse command line arguments with std::env.

Command Line Arguments

Parse command line arguments with std::env.

Difficulty

Beginner

Code

rust
use std::env;

fn main() {
    let args: Vec<String> = env::args().collect();
    println!("program: {}", args[0]);
    println!("args: {:?}", &args[1..]);

    if args.len() > 1 {
        println!("first arg: {}", args[1]);
    }
}

Explanation

std::env::args() returns command-line arguments.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the cli category to build a complete understanding of this topic.

More CLI Examples