0258-CLAP-关联参数
环境
- Time 2022-12-03
- WSL-Ubuntu 22.04
- CLAP 4.0.29
前言
说明
参考:https://docs.rs/clap/latest/clap/index.html
目标
设置两个参数相互关联。
Cargo.toml
[package]
edition = "2021"
name = "game"
version = "1.0.0"
[dependencies]
chrono = "0.4"
clap = {version = "4", features = ["cargo"]}
main.rs
use chrono::prelude::*;
use clap::{command, value_parser, Arg, ArgGroup};
fn main() {
let matches = command!()
.arg(
Arg::new("age")
.short('a')
.value_parser(value_parser!(u8))
.help("年龄"),
)
.arg(
Arg::new("year")
.short('y')
.value_parser(value_parser!(i32))
.help("出生年"),
)
.group(ArgGroup::new("born").required(true).args(["age", "year"]))
.get_matches();
if let Some(param) = matches.get_one::<u8>("age") {
println!("年龄是:{}", param);
let year = Local::now().year();
println!("出生年是:{}", year - *param as i32);
} else {
let year = matches.get_one::<i32>("year").unwrap();
println!("年龄是:{}", Local::now().year() - year);
println!("出生年是:{}", year);
}
}
查看帮助
root@jiangbo12490:~/git/game# cargo run -- -h
Compiling game v1.0.0 (/root/git/game)
Finished dev [unoptimized + debuginfo] target(s) in 0.50s
Running `target/debug/game -h`
Usage: game <-a <age>|-y <year>>
Options:
-a <age> 年龄
-y <year> 出生年
-h, --help Print help information
-V, --version Print version information
使用
root@jiangbo12490:~/git/game# cargo run -- -a 44
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/game -a 44`
年龄是:44
出生年是:1978
root@jiangbo12490:~/git/game# cargo run -- -y 1978
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/game -y 1978`
年龄是:44
出生年是:1978
root@jiangbo12490:~/git/game# cargo run -- -y 1978 -a 44
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/game -y 1978 -a 44`
error: The argument '-y <year>' cannot be used with '-a <age>'
Usage: game <-a <age>|-y <year>>
For more information try '--help'
总结
设置两个参数相互关联。

浙公网安备 33010602011771号