Clap unable to handle the HashMap in derive

Basically, I'm trying to do this.

struct Opts {
    #[arg(long, help = "address for which the server would listen")]
    address: SocketAddr,
    #[arg(long, num_args = 2)]
    host: HashMap<Box<str>, PathBuf>

But it gives parser error. I want achieve to create a command like this prog --address --host /ad dist1 --host /bc dist2 .. . How to make it work?

Please always include the complete error from cargo build or running the program.

Upon digging I found out multiple values for each argument are not yet supported in Clap

1 Like

I believe Custom collections · Issue #3114 · clap-rs/clap · GitHub and Parsing option argument from "k:v,k:v,..." into HashMap<String, String> · clap-rs/clap · Discussion #4291 · GitHub are the clap issues tracking this. clap/examples/ at f45a32ec2c1506faf319d914d985927ed47b0b5e · clap-rs/clap · GitHub is an example of how to get something similar with Vec<(String, PathBuf)>.

Clap does support num_args which allows multiple values for one CLI arg. For example, if you change HashMap to a Vec<String> for instance, you will obtain a 4 length vector of your two pairs of host arguments. The issue is HashMap does not have a ValueParser implementation with which to parse the CLI args. @gibfahn's third link gives a useful alternative with a custom value_parser implementation.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.