Get a Single Command Line Argument with Clap in Rust
Helpful Arguments
clap1 is the Command Line Argument Parser for Rust. It has a billion and one ways to process arguments and flags. Even better, it provides nice error messages out of the box.
There's a bunch of great tutorials2 and a cookbook3 in the docs. As thorough as they are, I didn't see how to use it to get a single argument.
This is what I came up with after a quick dive into the docs:
#!/usr/bin/env cargo -Zscript
---
clap = "4.5.38"
---
use ;
Usage
If you drop that code in a file called runner.rs
and run it with:
./runner.rs some_thing
It'll output:
Bonus Features
Missing Things
Calling the script without an argument gives you an error:
./runner.rs
Automatic Help
Processing a --help
flag is built-in. It gives you nice output:
./runner.rs --help
One Ping Only
Clap is worth checking out for any and all your command line processing needs. I'd be surprised if you can come up with a realistic example it can't handle.
-a
Endnotes
This example is set up as a rust script. Yoink the top #!
line and move the dependencies into a Cargo.toml
file to use it in a traditional binary.
Clap provides a bunch of macros and a couple different ways to build argument parsers. This approach was the easiest for me to get working. You should kick around the docs though to get a feel for the different ways you can use the crate.
Also check out value_parser for validating incoming values.