Skip to content

Rust CLI Applications — Building CLI Tools with clap, structopt, and std::env

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about Rust CLI Applications. We cover key concepts, practical examples, and best practices to help you master this topic.

Rust CLI apps use clap for argument Parsing, structopt for derive-based config, and std::env for environment variable access.

What You'll Learn

  • clap derive API
  • Subcommands
  • Environment variables
  • CLI output

Why It Matters

Rust is great for CLI tools. ripgrep, fd, and bat are Rust CLIs. DodaZIP offers a CLI for file processing.

Real-World Use

DevOps tools, code analysis, file processing, build tools.

[dependencies]
clap = { version = "4.0", features = ["derive"] }
use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(name = "myapp")]
#[command(about = "A CLI tool", version = "1.0")]
struct Cli {
    #[arg(short, long)]
    name: Option<String>,

    #[arg(short, long, default_value = "1")]
    count: u32,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    Greet { name: String },
    Sum { numbers: Vec<i32> },
}

fn main() {
    let cli = Cli::parse();

    match &cli.command {
        Some(Commands::Greet { name }) => {
            println!("Hello, {}!", name);
        }
        Some(Commands::Sum { numbers }) => {
            let sum: i32 = numbers.iter().sum();
            println!("Sum: {}", sum);
        }
        None => {
            for _ in 0..cli.count {
                let name = cli.name.as_deref().unwrap_or("World");
                println!("Hello, {}!", name);
            }
        }
    }
}

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro