How are the positional arguments to struct Cli
matched to the fields _in order_ ?
#6113
-
Somewhat new to Rust and Clap. I find the tool superb so far, and can only thank you for it. There is an example I didn't understand from the tutorial, and I wonder if you could explain it. It just looks a bit magical an aspect of the [positional arguments]((https://docs.rs/clap/latest/clap/_derive/_tutorial/index.html#positionals). For example, use clap::Parser;
#[derive(Parser)]
#[command()]
struct Cli {
name: Option<String>,
surname: Option<String>,
}
fn main() {
let cli = Cli::parse();
if let Some(name) = cli.name {
println!("Name: {name}");
}
if let Some(surname) = cli.surname {
println!("Surname: {surname}");
}
} So in struct Cli {
surname: Option<String>,
name: Option<String>,
} It reverses the print to This is probably a basic question, but I don't quite see how do you obtain the names of the struct in order they are declared in the text ?! Just a small conceptual explanation would be enough for me, but got me stuck pondering that. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Beta Was this translation helpful? Give feedback.
#[derive(Parser)]
activates a compiler plugin,clap_derive
and passes a copy of the Rust Tokens for the entire struct to that plugin. We then iterate on them in order to provide this.