docs(derive): Clarify subcommand arg syntax

This commit is contained in:
Ed Page 2022-02-22 08:23:58 -06:00
parent 655c3f0b9f
commit e8218733c2
3 changed files with 41 additions and 0 deletions

View file

@ -309,6 +309,11 @@ name = "03_04_subcommands_derive"
path = "examples/tutorial_derive/03_04_subcommands.rs"
required-features = ["derive"]
[[example]]
name = "03_04_subcommands_alt_derive"
path = "examples/tutorial_derive/03_04_subcommands_alt.rs"
required-features = ["derive"]
[[example]]
name = "03_05_default_values_derive"
path = "examples/tutorial_derive/03_05_default_values.rs"

View file

@ -0,0 +1,32 @@
use clap::{Parser, Subcommand, Args};
#[derive(Parser)]
#[clap(author, version, about, long_about = None)]
#[clap(propagate_version = true)]
struct Cli {
#[clap(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Adds files to myapp
Add(Add),
}
#[derive(Args)]
struct Add {
name: Option<String>
}
fn main() {
let cli = Cli::parse();
// You can check for the existence of subcommands, and if found use their
// matches just as you would the top level cmd
match &cli.command {
Commands::Add { name } => {
println!("'myapp add' was used, name is: {:?}", name)
}
}
}

View file

@ -306,6 +306,10 @@ $ 03_04_subcommands_derive add bob
```
Above, we used a struct-variant to define the `add` subcommand. Alternatively,
you can
[use a struct for your subcommand's arguments](03_04_subcommands_alt_derive.rs).
Because we used `command: Commands` instead of `command: Option<Commands>`:
```console
$ 03_04_subcommands_derive