0262-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 = ["derive"]}

main.rs

use clap::Parser;

/// 命令行参数
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Args {
    /// 姓名
    name: String,

    /// 年龄,可选参数
    age: Option<u8>,

    /// 是不是青少年
    #[arg(short, long)]
    teens: bool,

    /// 国家,默认参数
    #[arg(short, long, default_value_t = String::from("中国"))]
    country: String,

    /// 调试模式,计数参数
    #[arg(short, long, action = clap::ArgAction::Count)]
    verbose: u8,
}

fn main() {
    let args = Args::parse();
    println!("姓名是:{}", args.name);
    println!("年龄是:{:?}", args.age);
    println!("青少年:{:?}", args.teens);
    println!("国家是:{:?}", args.country);
    println!("次数是:{:?}", args.verbose);
}

查看帮助

root@jiangbo12490:~/git/game# cargo run -- -h
   Compiling game v1.0.0 (/root/git/game)
    Finished dev [unoptimized + debuginfo] target(s) in 0.53s
     Running `target/debug/game -h`
命令行参数

Usage: game [OPTIONS] <NAME> [AGE]

Arguments:
  <NAME>  姓名
  [AGE]   年龄,可选参数

Options:
  -t, --teens              是不是青少年
  -c, --country <COUNTRY>  国家,默认参数 [default: 中国]
  -v, --verbose...         调试模式,计数参数
  -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 '张三'`
姓名是:张三
年龄是:None
青少年:false
国家是:"中国"
次数是:0
root@jiangbo12490:~/git/game# cargo run -- 张三 44
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/game '张三' 44`
姓名是:张三
年龄是:Some(44)
青少年:false
国家是:"中国"
次数是:0
root@jiangbo12490:~/git/game# cargo run -- 张三 44 -t
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/game '张三' 44 -t`
姓名是:张三
年龄是:Some(44)
青少年:true
国家是:"中国"
次数是:0
root@jiangbo12490:~/git/game# cargo run -- 张三 44 -t -v -v -v
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/game '张三' 44 -t -v -v -v`
姓名是:张三
年龄是:Some(44)
青少年:true
国家是:"中国"
次数是:3

总结

使用注解来定义了命令行的各种参数并解析打印出来。

附录

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