Rust CLI Tool with Clap

Build a command-line tool in Rust using Clap with derive macros for subcommands, typed arguments, environment variable fallback, colored output, and shell.

RustCli Tooling

Code

snippet
use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(name = "mycli", version = "1.0")]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    Build { input: String, #[arg(short, long, default_value = "dist")] output: String },
    Deploy { #[arg(long)] verbose: bool },
}

fn main() {
    let cli = Cli::parse();
    match cli.command {
        Commands::Build { input, output } => println!("Building {input} → {output}"),
        Commands::Deploy { verbose } => println!("Deploying (verbose: {verbose})"),
    }
}

How it works

Count the function main as the entire surface area of Rust CLI Tool with Clap.

Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

Caveats

  • clap:: must be installed first — the snippet imports it directly.

Putting it to use

The demo output is labeled (Building, Deploying (verbose:), so every printed line maps back to its originating operation.

Core lines

match cli.command {
Commands::Build { input, output } => println!("Building {input} → {output}"),
Commands::Deploy { verbose } => println!("Deploying (verbose: {verbose})"),
}

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
Yes: `clap::` must be present in the project or the import fails at load time.