Command Line Flags in Rust
Here’s the translation of the Go code to Rust, along with explanations in Markdown format suitable for Hugo:
Command-line flags are a common way to specify options for command-line programs. For example, in wc -l
the -l
is a command-line flag.
Rust provides the clap
crate for parsing command-line arguments. We’ll use this crate to implement our example command-line program.
use clap::Parser;
/// Simple program to greet a person
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Args {
/// Name of the person to greet
#[clap(short, long, default_value = "foo")]
word: String,
/// Number of times to greet
#[clap(short, long, default_value_t = 42)]
numb: i32,
/// Whether to fork
#[clap(short, long)]
fork: bool,
/// Another string option
#[clap(short, long, default_value = "bar")]
svar: String,
}
fn main() {
let args = Args::parse();
println!("word: {}", args.word);
println!("numb: {}", args.numb);
println!("fork: {}", args.fork);
println!("svar: {}", args.svar);
println!("tail: {:?}", std::env::args().skip(1).collect::<Vec<String>>());
}
To experiment with the command-line flags program, it’s best to first compile it and then run the resulting binary directly.
$ cargo build --release
Try out the built program by first giving it values for all flags.
$ ./target/release/command-line-flags --word=opt --numb=7 --fork --svar=flag
word: opt
numb: 7
fork: true
svar: flag
tail: []
Note that if you omit flags, they automatically take their default values.
$ ./target/release/command-line-flags --word=opt
word: opt
numb: 42
fork: false
svar: bar
tail: []
Trailing positional arguments can be provided after any flags.
$ ./target/release/command-line-flags --word=opt a1 a2 a3
word: opt
...
tail: ["a1", "a2", "a3"]
Use -h
or --help
flags to get automatically generated help text for the command-line program.
$ ./target/release/command-line-flags -h
command-line-flags 0.1.0
USAGE:
command-line-flags [OPTIONS]
OPTIONS:
-f, --fork Whether to fork
-h, --help Print help information
-n, --numb <NUMB> Number of times to greet [default: 42]
-s, --svar <SVAR> Another string option [default: bar]
-V, --version Print version information
-w, --word <WORD> Name of the person to greet [default: foo]
If you provide a flag that wasn’t specified to the clap
crate, the program will print an error message and show the help text again.
$ ./target/release/command-line-flags --wat
error: Found argument '--wat' which wasn't expected, or isn't valid in this context
USAGE:
command-line-flags [OPTIONS]
For more information try --help
In this Rust version, we use the clap
crate which provides a more declarative way to define command-line arguments. The #[derive(Parser)]
attribute automatically generates the parsing logic based on the struct definition. This approach is idiomatic in Rust and provides a type-safe way to handle command-line arguments.