0256-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, Arg};

fn main() {
    let matches = command!()
        .arg(Arg::new("name").value_parser(["张三", "李四"]).help("姓名"))
        .get_matches();

    if let Some(param) = matches.get_one::<String>("name") {
        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.44s
     Running `target/debug/game -h`
Usage: game [name]

Arguments:
  [name]  姓名 [possible values: 张三, 李四]

Options:
  -h, --help     Print help information
  -V, --version  Print version information

使用

root@jiangbo12490:~/git/game# cargo run 张三
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/game '张三'`
set 的姓名是: 张三
root@jiangbo12490:~/git/game# cargo run 王五
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/game '王五'`
error: '王五' isn't a valid value for '[name]'
  [possible values: 张三, 李四]

For more information try '--help'

总结

限制参数可以输入的值有哪些。

附录

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