Subcommands map a command word to a specific action, with a fallback for unknown input.

Program

Play the program to choose a command and route it to an action string.

command
cli_subcommand_router.rs
Replay: real traced execution (multi-file project)
fn main() {
    let command = "build";
    let action = route(command);
    println!("{action}");
}

fn route(command: &str) -> &'static str {
    match command {
        "build" => "compile project",
        "test" => "run tests",
        "clean" => "remove artifacts",
        _ => "show help",
    }
}
fn main() {
    let command = "test";
    let action = route(command);
    println!("{action}");
}

fn route(command: &str) -> &'static str {
    match command {
        "build" => "compile project",
        "test" => "run tests",
        "clean" => "remove artifacts",
        _ => "show help",
    }
}
fn main() {
    let command = "clean";
    let action = route(command);
    println!("{action}");
}

fn route(command: &str) -> &'static str {
    match command {
        "build" => "compile project",
        "test" => "run tests",
        "clean" => "remove artifacts",
        _ => "show help",
    }
}
  1. command ← "build"

    1fn main() {2    let comman→ "build"d = "build"; //@command="build", "test", "clean"3    let action = route(comman"build"d);4    println!("{action}");
  2. action ← "compile project"

    2    let command = "build"; //@command="build", "test", "clean"3    let actio→ "compile project"n = route(comman"build"d);4    println!("{action}");5}
    outputcompile project
  1. command ← "test"

    1fn main() {2    let comman→ "test"d = "test";3    let action = route(comman"test"d);4    println!("{action}");
  2. action ← "run tests"

    2    let command = "test";3    let actio→ "run tests"n = route(comman"test"d);4    println!("{action}");5}
    outputrun tests
  1. command ← "clean"

    1fn main() {2    let comman→ "clean"d = "clean";3    let action = route(comman"clean"d);4    println!("{action}");
  2. action ← "remove artifacts"

    2    let command = "clean";3    let actio→ "remove artifacts"n = route(comman"clean"d);4    println!("{action}");5}
    outputremove artifacts
subcommand The command word chooses the action branch.
router `route` centralizes the command-to-action mapping.
fallback A wildcard branch can handle unknown command words.