环境
- 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 std::ops::RangeInclusive;use clap::{command, Arg};fn main() {let matches = command!().arg(Arg::new("age").value_parser(age_in_range).help("年龄")).get_matches();if let Some(param) = matches.get_one::<u8>("age") {println!("年龄是:{}", param);}
}const AGE_RANGE: RangeInclusive<usize> = 0..=200;fn age_in_range(age: &str) -> Result<u8, String> {let age: usize = age.parse().map_err(|_| format!("`{}` isn't a number", age))?;if AGE_RANGE.contains(&age) {Ok(age as u8)} else {Err(format!("Age not in range {}-{}",AGE_RANGE.start(),AGE_RANGE.end()))}
}
查看帮助
root@jiangbo12490:~/git/game# cargo run -- -hCompiling game v1.0.0 (/root/git/game)Finished dev [unoptimized + debuginfo] target(s) in 0.44sRunning `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 -- jjFinished dev [unoptimized + debuginfo] target(s) in 0.01sRunning `target/debug/game jj`
error: Invalid value 'jj' for '[age]': `jj` isn't a numberFor more information try '--help'
root@jiangbo12490:~/git/game# cargo run -- 288Finished dev [unoptimized + debuginfo] target(s) in 0.01sRunning `target/debug/game 288`
error: Invalid value '288' for '[age]': Age not in range 0-200For more information try '--help'
root@jiangbo12490:~/git/game# cargo run -- 28Finished dev [unoptimized + debuginfo] target(s) in 0.01sRunning `target/debug/game 28`
年龄是:28
总结
自定义参数的校验逻辑。