0259-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 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 -- -h
   Compiling game v1.0.0 (/root/git/game)
    Finished dev [unoptimized + debuginfo] target(s) in 0.44s
     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 -- jj
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/game jj`
error: Invalid value 'jj' for '[age]': `jj` isn't a number

For more information try '--help'
root@jiangbo12490:~/git/game# cargo run -- 288
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/game 288`
error: Invalid value '288' for '[age]': Age not in range 0-200

For more information try '--help'
root@jiangbo12490:~/git/game# cargo run -- 28
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/game 28`
年龄是:28

总结

自定义参数的校验逻辑。

附录

posted @ 2025-10-23 10:13  jiangbo4444  阅读(3)  评论(0)    收藏  举报