0Pricing
Learn Rust Coding · Lesson

Subcommands

Structured CLIs.

Subcommands is a free Learn Rust Coding lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What are subcommands?

Subcommands let one binary expose several actions, like git commit and git push.

  • Each subcommand has its own arguments
  • The structure scales as your CLI grows

clap models these with nested Command values.

Adding a subcommand

Attach a child command with .subcommand(). The parent becomes a dispatcher.

use clap::Command;

fn main() {
    Command::new("todo")
        .subcommand(Command::new("add"))
        .subcommand(Command::new("list"))
        .get_matches();
}

Matching the chosen subcommand

After parsing, subcommand() tells you which child ran. Match on its name to dispatch.

use clap::Command;

fn main() {
    let m = Command::new("todo")
        .subcommand(Command::new("add"))
        .subcommand(Command::new("list"))
        .get_matches();
    match m.subcommand() {
        Some(("add", _)) => println!("adding"),
        Some(("list", _)) => println!("listing"),
        _ => println!("no subcommand"),
    }
}

Args inside a subcommand

A subcommand carries its own arguments. The add command below takes a task description.

use clap::{Command, Arg};

fn main() {
    Command::new("todo")
        .subcommand(
            Command::new("add")
                .arg(Arg::new("task").required(true))
        )
        .get_matches();
}

Reading subcommand args

The second tuple element is the sub-ArgMatches. Pull values from it just like the top level.

use clap::{Command, Arg};

fn main() {
    let m = Command::new("todo")
        .subcommand(Command::new("add").arg(Arg::new("task")))
        .get_matches();
    if let Some(("add", sub)) = m.subcommand() {
        let task = sub.get_one::<String>("task").unwrap();
        println!("add: {}", task);
    }
}

Requiring a subcommand

Use subcommand_required(true) so running the bare binary prints help instead of doing nothing.

use clap::Command;

fn main() {
    Command::new("todo")
        .subcommand_required(true)
        .arg_required_else_help(true)
        .subcommand(Command::new("list"))
        .get_matches();
}

Modeling dispatch in plain Rust

The core of a subcommand CLI is a match on a string. This runnable example mirrors that dispatch logic.

fn main() {
    let cmd = "add";
    let task = "Buy milk";
    match cmd {
        "add" => println!("Added: {}", task),
        "list" => println!("Listing tasks"),
        other => println!("Unknown command: {}", other),
    }
}

Nested subcommands

Subcommands can themselves have subcommands, e.g. cargo build --release vs deeper trees. Just nest more .subcommand() calls.

use clap::Command;

fn main() {
    Command::new("app")
        .subcommand(
            Command::new("config")
                .subcommand(Command::new("get"))
                .subcommand(Command::new("set"))
        )
        .get_matches();
}

Per-subcommand help

Each subcommand gets its own --help page. Add an about string to describe it.

use clap::Command;

fn main() {
    Command::new("todo")
        .subcommand(
            Command::new("add").about("Add a new task")
        )
        .get_matches();
}

Aliases

Give users shortcuts with visible_alias. Now ls works as well as list.

use clap::Command;

fn main() {
    Command::new("todo")
        .subcommand(
            Command::new("list").visible_alias("ls")
        )
        .get_matches();
}

Returning exit codes

A polished CLI signals success or failure. Return a non-zero code from a subcommand using std::process::exit or by returning Result from main.

fn main() {
    let success = true;
    if !success {
        std::process::exit(1);
    }
    println!("ok");
}

Quick Check

Test your understanding of subcommands.

Recap

You now build structured CLIs with subcommands:

  • Add children with .subcommand()
  • Dispatch by matching m.subcommand()
  • Each subcommand has its own args and help page
  • Use subcommand_required and aliases for polish

Next: the derive API turns structs into argument parsers.

Frequently asked questions

Is the “Subcommands” lesson free?

Yes — the full text of “Subcommands” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.

What will I learn in “Subcommands”?

Structured CLIs. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Learn Rust Coding?

No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Subcommands” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Learn Rust Coding lesson?

Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. clap Basics
  2. Subcommands
  3. Derive API
  4. Validation and Help
← Back to Learn Rust Coding