mirror of
https://github.com/clap-rs/clap
synced 2024-11-10 06:44:16 +00:00
docs(derive): Clarify subcommand arg syntax
This commit is contained in:
parent
655c3f0b9f
commit
e8218733c2
3 changed files with 41 additions and 0 deletions
|
@ -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"
|
||||
|
|
32
examples/tutorial_derive/03_04_subcommands_alt.rs
Normal file
32
examples/tutorial_derive/03_04_subcommands_alt.rs
Normal 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)
|
||||
}
|
||||
}
|
||||
}
|
|
@ -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
|
||||
|
|
Loading…
Reference in a new issue