Skip to main content Building a CLI Application | Rust Fundamentals lesson | BraveProgrammerBuilding a CLI Application
25 minutes
Building a CLI Application
Use the clap crate to parse arguments and subcommands.
[dependencies]
clap = { version = "4.0", features = ["derive"] }
use clap::{Parser, Subcommand};
#[derive(Parser)]
#[command(name = \"calc\")]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
Add { a: i32, b: i32 },
Sub { a: i32, b: i32 },
}
fn main() {
let cli = Cli::parse();
match cli.command {
Commands::Add { a, b } => println!(\"{} + {} = {}\", a, b, a + b),
Commands::Sub { a, b } => println!(\"{} - {} = {}\", a, b, a - b),
}
}
Make it stickPractice what you've learned1 quiz · 1 practical test · Optional activities from Rust FundamentalsBrowse activities