Lesson 31 of 50 · rust
Building a CLI Application
Duration: 25 minutes
Lesson 31 of 50 · rust
Duration: 25 minutes
clap crate to parse arguments and subcommands.\n\ntoml\n# Cargo.toml\n[dependencies]\nclap = { version = "4.0", features = ["derive"] }\n\n\nrust\nuse clap::{Parser, Subcommand};\n\n#[derive(Parser)]\n#[command(name = \"calc\")]\nstruct Cli {\n #[command(subcommand)]\n command: Commands,\n}\n\n#[derive(Subcommand)]\nenum Commands {\n Add { a: i32, b: i32 },\n Sub { a: i32, b: i32 },\n}\n\nfn main() {\n let cli = Cli::parse();\n match cli.command {\n Commands::Add { a, b } => println!(\"{} + {} = {}\", a, b, a + b),\n Commands::Sub { a, b } => println!(\"{} - {} = {}\", a, b, a - b),\n }\n}\n\n