Search code examples
rustclap

How to Get Matches From a Parser Derived Struct?


The documentation has got me confused. I'm kind of stuck on how to get matches from a parser derived struct. How would I go about doing this? Here's what my argument struct looks like.

#[derive(Parser)]
#[clap(author, version, about, long_about = None)]
pub struct Args {
    /// Host address
    #[clap(short, long)]
    pub host: String,
    /// Database username
    #[clap(short, long)]
    pub username: String,
    /// Database password
    #[clap(short='P', long)]
    pub password: String,
    /// Database name
    #[clap(short='d', long)]
    pub database: String,
    /// Database port number
    #[clap(short, long, default_value_t = 3306)]
    pub port: u32,
}

Solution

  • The clap::Parser trait has a method parse that you can use, that will read the arguments into a structure of the type, or exit the process on error.

    use clap::Parser;
    
    #[derive(Parser)]
    #[clap(author, version, about, long_about = None)]
    pub struct Args {
        /// Host address
        #[clap(short, long)]
        pub host: String,
        ...
    }
    
    fn main() {
      let args = Args::parse();
      println!("got host: {}", args.host);
    }