Introduction

Clap is a very powerful command line parser, written in Rust.

You can find its documentation here.

To better understand how it works, let’s create a simple CLI program that takes a string as input and, depending on the command, reverse or inspect it.

Repo

Here you can find the full code: Github!

Clone the repo and try it your self to see how it works in practice.

Naive approach

Note: it’s not wrong, just not recommended since it is much more verbose and difficult to understand. Still it’s very useful to study because it shows the real generated code.

Define commands, arguments and flags

let matches = command!()
		.about("stringer - a simple CLI to transform and inspect strings")
		.long_about(
		    "stringer is a super fancy CLI (kidding)
		
		One can use stringer to modify or inspect strings straight from the terminal",
		)
		.subcommand(
		    Command::new("reverse")
		        .about("Reverses a string")
		        .arg(arg!([STRING] "The string to reverse")),
		)
		.subcommand(
		    Command::new("inspect")
		        .about("Inspects a string")
		        .arg(arg!([STRING] "The string to inspect"))
		        .arg(arg!(-d --digits "only digits")),
		)
		.get_matches();

Let’s break it down step-by-step: