
Building a Typed Command Registry in Rust with clap
Rust applications often grow from a single binary into a small suite of operational commands: database migrations, cache warmups, maintenance jobs, diagnostics, and administrative tasks. A typed command registry gives you a clean way to model those commands as Rust values instead of ad hoc string matching.
In this tutorial, you’ll build a small but practical command registry that maps command names to strongly typed handlers. The result is useful for CLI tools, plugin-like systems, and internal automation binaries where you want compile-time structure without sacrificing runtime flexibility.
Why a typed command registry?
A command registry is a lookup table that connects a command identifier such as backup or reindex to executable logic. In a typed design, each command carries structured data rather than a loose list of strings and flags.
This approach helps when you need:
- predictable command dispatch
- validation before execution
- reusable command metadata
- a clear separation between parsing and business logic
Compared with a stringly typed HashMap<String, Box<dyn Fn(...)>>, a typed registry makes illegal states harder to represent and easier to reject early.
What we are building
We will create a registry that supports:
- registering commands by name
- attaching a typed payload to each command
- dispatching commands through a common trait
- listing available commands for help output
The example will use clap only for argument parsing. The registry itself will be independent of clap, which keeps the design reusable in tests and non-CLI contexts.
Define the command model
Start by defining a command trait and a registry entry type. Each command will implement a common interface so the registry can store them uniformly.
use std::collections::HashMap;
pub trait Command {
fn name(&self) -> &'static str;
fn description(&self) -> &'static str;
fn execute(&self) -> Result<(), String>;
}
pub struct CommandRegistry {
commands: HashMap<&'static str, Box<dyn Command>>,
}
impl CommandRegistry {
pub fn new() -> Self {
Self {
commands: HashMap::new(),
}
}
pub fn register<C>(&mut self, command: C)
where
C: Command + 'static,
{
self.commands.insert(command.name(), Box::new(command));
}
pub fn get(&self, name: &str) -> Option<&dyn Command> {
self.commands.get(name).map(|cmd| cmd.as_ref())
}
pub fn list(&self) -> Vec<(&'static str, &'static str)> {
let mut items: Vec<_> = self
.commands
.values()
.map(|cmd| (cmd.name(), cmd.description()))
.collect();
items.sort_by_key(|(name, _)| *name);
items
}
}
This design keeps the registry simple:
name()is the lookup keydescription()supports help textexecute()contains the actual behavior
The CommandRegistry stores trait objects, which is appropriate here because commands are heterogeneous but share a common interface.
Add concrete commands with typed state
Now define a few real commands. Each command can carry its own typed configuration.
pub struct BackupCommand {
pub target_dir: String,
pub compress: bool,
}
impl Command for BackupCommand {
fn name(&self) -> &'static str {
"backup"
}
fn description(&self) -> &'static str {
"Create a backup of the data directory"
}
fn execute(&self) -> Result<(), String> {
if self.target_dir.is_empty() {
return Err("target_dir must not be empty".into());
}
if self.compress {
println!("Backing up to {} with compression enabled", self.target_dir);
} else {
println!("Backing up to {} without compression", self.target_dir);
}
Ok(())
}
}
pub struct ReindexCommand {
pub index_name: String,
pub dry_run: bool,
}
impl Command for ReindexCommand {
fn name(&self) -> &'static str {
"reindex"
}
fn description(&self) -> &'static str {
"Rebuild a search index"
}
fn execute(&self) -> Result<(), String> {
if self.index_name.is_empty() {
return Err("index_name must not be empty".into());
}
if self.dry_run {
println!("Would reindex {}", self.index_name);
} else {
println!("Reindexing {}", self.index_name);
}
Ok(())
}
}
This is where the typed design pays off. Instead of passing a generic map of flags into every handler, each command owns exactly the data it needs.
Parse CLI input with clap
Next, use clap to parse a minimal command-line interface. We’ll accept a command name and a few command-specific arguments.
Add the dependency:
[dependencies]
clap = { version = "4", features = ["derive"] }
Then define the CLI structure:
use clap::{Parser, Subcommand};
#[derive(Parser)]
#[command(name = "opsctl", version, about = "Operational command runner")]
struct Cli {
#[command(subcommand)]
command: Option<CommandArgs>,
}
#[derive(Subcommand)]
enum CommandArgs {
Backup {
#[arg(long)]
target_dir: String,
#[arg(long, default_value_t = false)]
compress: bool,
},
Reindex {
#[arg(long)]
index_name: String,
#[arg(long, default_value_t = false)]
dry_run: bool,
},
}
This CLI layer is intentionally thin. It validates syntax and converts raw arguments into typed Rust values. The registry then turns those values into executable commands.
Bridge parsed arguments to registry entries
The registry is most useful when it can construct commands from parsed input. One clean pattern is to convert CommandArgs into boxed command instances.
impl CommandArgs {
pub fn into_command(self) -> Box<dyn Command> {
match self {
CommandArgs::Backup {
target_dir,
compress,
} => Box::new(BackupCommand {
target_dir,
compress,
}),
CommandArgs::Reindex {
index_name,
dry_run,
} => Box::new(ReindexCommand {
index_name,
dry_run,
}),
}
}
}
This keeps parsing and execution separate:
clapparses and validates CLI syntaxinto_command()converts parsed data into a typed commandexecute()performs the work
That separation makes the code easier to test and extend.
Wire everything together
Here is a complete example showing registration, dispatch, and help output.
use clap::Parser;
fn build_registry() -> CommandRegistry {
let mut registry = CommandRegistry::new();
registry.register(BackupCommand {
target_dir: "/var/backups".into(),
compress: true,
});
registry.register(ReindexCommand {
index_name: "products".into(),
dry_run: false,
});
registry
}
fn main() {
let cli = Cli::parse();
let registry = build_registry();
match cli.command {
Some(command_args) => {
let command = command_args.into_command();
if let Err(err) = command.execute() {
eprintln!("command failed: {err}");
std::process::exit(1);
}
}
None => {
println!("Available commands:");
for (name, description) in registry.list() {
println!(" {:<10} {}", name, description);
}
}
}
}
This example uses a prebuilt registry for demonstration, but the same pattern works with dynamic registration from plugins, configuration files, or feature-gated modules.
A better pattern for larger systems
For larger applications, you may want to avoid storing command-specific data directly in the registry. Instead, store factories that build commands from typed input. This is useful when the command depends on runtime context such as a database pool, logger, or filesystem root.
| Pattern | Best for | Tradeoff |
|---|---|---|
| Store concrete commands | Small tools, fixed command sets | Less flexible for runtime dependencies |
| Store command factories | Larger apps, dependency injection | Slightly more boilerplate |
| Store trait objects only | Plugin-style dispatch | Harder to inspect command-specific data |
A factory-based registry might look like this:
pub trait CommandFactory {
fn name(&self) -> &'static str;
fn description(&self) -> &'static str;
fn build(&self, args: CommandArgs) -> Result<Box<dyn Command>, String>;
}
This pattern is especially useful when commands need shared services such as a connection pool or a metrics client.
Best practices for typed registries
A few practical guidelines will keep the design maintainable:
Keep parsing separate from execution
Let clap or another parser handle raw input. Convert into typed structures before dispatching. This reduces duplication and makes error handling more consistent.
Prefer small command types
Each command should own only the data it needs. If a command struct starts accumulating unrelated fields, split it into smaller commands or introduce a shared context object.
Use descriptive errors
Return actionable errors from execute(). For example, index_name must not be empty is much better than a generic failure message.
Make listing deterministic
Sort command names before printing help or diagnostics. Deterministic output is easier to test and friendlier for users.
Avoid overusing dynamic dispatch
Trait objects are appropriate for heterogeneous commands, but if your command set is closed and small, an enum may be simpler and faster. Choose the design that matches your extension needs.
Testing the registry
Typed registries are easy to test because each layer has a narrow responsibility. You can test parsing, registration, and execution separately.
Example unit tests:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn registry_lists_commands_in_order() {
let mut registry = CommandRegistry::new();
registry.register(ReindexCommand {
index_name: "products".into(),
dry_run: true,
});
registry.register(BackupCommand {
target_dir: "/tmp".into(),
compress: false,
});
let names: Vec<_> = registry.list().into_iter().map(|(name, _)| name).collect();
assert_eq!(names, vec!["backup", "reindex"]);
}
#[test]
fn backup_command_rejects_empty_target() {
let cmd = BackupCommand {
target_dir: String::new(),
compress: true,
};
assert!(cmd.execute().is_err());
}
}
These tests focus on behavior rather than implementation details. That makes them resilient to refactoring.
When to use this pattern
A typed command registry is a strong fit when you need:
- a CLI with multiple operational subcommands
- internal tooling with reusable command logic
- a plugin-like architecture with a known command interface
- explicit validation before execution
It is less useful when your application has only one or two commands and no need for runtime dispatch. In that case, a direct match on clap subcommands may be simpler.
Summary
A typed command registry gives Rust developers a disciplined way to organize command-driven applications. By combining clap for parsing with typed command structs and a registry for dispatch, you get:
- clearer boundaries between input and execution
- better validation
- easier testing
- a scalable path from small tools to larger operational systems
The core idea is simple: parse into typed data, register typed behavior, and execute through a narrow interface. That structure keeps your codebase predictable as the number of commands grows.