docs(tutorial): Provide better default_value_t example

This commit is contained in:
Ed Page 2022-09-16 16:14:01 -05:00
parent acb0fb7809
commit 3cadb8f255
4 changed files with 21 additions and 17 deletions

View file

@ -2,19 +2,19 @@
$ 03_05_default_values --help
A simple to use, efficient, and full-featured Command Line Argument Parser
Usage: 03_05_default_values[EXE] [NAME]
Usage: 03_05_default_values[EXE] [PORT]
Arguments:
[NAME] [default: alice]
[PORT] [default: 2020]
Options:
-h, --help Print help information
-V, --version Print version information
$ 03_05_default_values
name: "alice"
port: 2020
$ 03_05_default_values bob
name: "bob"
$ 03_05_default_values 22
port: 22
```

View file

@ -1,14 +1,18 @@
use clap::{arg, command};
use clap::{arg, command, value_parser};
fn main() {
let matches = command!() // requires `cargo` feature
.arg(arg!([NAME]).default_value("alice"))
.arg(
arg!([PORT])
.value_parser(value_parser!(u16))
.default_value("2020"),
)
.get_matches();
println!(
"name: {:?}",
"port: {:?}",
matches
.get_one::<String>("NAME")
.get_one::<u16>("PORT")
.expect("default ensures there is always a value")
);
}

View file

@ -2,19 +2,19 @@
$ 03_05_default_values_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser
Usage: 03_05_default_values_derive[EXE] [NAME]
Usage: 03_05_default_values_derive[EXE] [PORT]
Arguments:
[NAME] [default: alice]
[PORT] [default: 2020]
Options:
-h, --help Print help information
-V, --version Print version information
$ 03_05_default_values_derive
name: "alice"
port: 2020
$ 03_05_default_values_derive bob
name: "bob"
$ 03_05_default_values_derive 22
port: 22
```

View file

@ -3,12 +3,12 @@ use clap::Parser;
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
#[arg(default_value_t = String::from("alice"))]
name: String,
#[arg(default_value_t = 2020)]
port: u16,
}
fn main() {
let cli = Cli::parse();
println!("name: {:?}", cli.name);
println!("port: {:?}", cli.port);
}