Clap - Add help text for each command line parameter in Rust

help arg

Part of the series about Clap, the Command Line Argument Parser of Rust

As we already saw in the first article in the series Clap automatically provides a default help that can be shown using either the --help or the -h command line parameter. We can easily add extra explanation to each one of the flags by including the help attribute in the arg.

#[arg(long, default_value="127.0.0.1", help="The name of the host")]
host: String,

Dependencies in the Cargo.toml file

examples/clap/help-text/Cargo.toml

[package]
name = "help-text"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
clap = { version = "4.4.11", features = ["derive"] }

The full example

examples/clap/help-text/src/main.rs

use clap::Parser;

#[derive(Parser)]
struct Cli {
    #[arg(long, default_value="127.0.0.1", help="The name of the host")]
    host: String,
}

fn main() {
    let args = Cli::parse();
    println!("{}", args.host);
}

Showing the help

$ cargo run -q -- -h
Usage: help-text [OPTIONS]

Options:
      --host <HOST>  The name of the host [default: 127.0.0.1]
  -h, --help         Print help

Related Pages

Clap - getting started accepting command line parameters in Rust
Clap - Command Line Argument Parser for Rust

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo