0257-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]
clap = {version = "4", features = ["cargo"]}
main.rs
use clap::{command, value_parser, Arg};
fn main() {
let matches = command!()
.arg(
Arg::new("age")
.value_parser(value_parser!(u8).range(0..200))
.help("年龄"),
)
.get_matches();
if let Some(param) = matches.get_one::<u8>("age") {
println!("set 的年龄是: {}", param);
}
}
查看帮助
root@jiangbo12490:~/git/game# cargo run -- -h
Compiling game v1.0.0 (/root/git/game)
Finished dev [unoptimized + debuginfo] target(s) in 0.40s
Running `target/debug/game -h`
Usage: game [age]
Arguments:
[age] 年龄
Options:
-h, --help Print help information
-V, --version Print version information
使用
root@jiangbo12490:~/git/game# cargo run 255
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/game 255`
error: Invalid value '255' for '[age]': 255 is not in 0..200
For more information try '--help'
root@jiangbo12490:~/git/game# cargo run 25
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/game 25`
set 的年龄是: 25
总结
校验输入参数的范围。

浙公网安备 33010602011771号