0265-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]
chrono = "0.4.23"
clap = {version = "4", features = ["derive"]}

main.rs

use chrono::{Datelike, Local};
use clap::{ArgGroup, Parser};

/// 命令行参数
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
#[command(group(
    ArgGroup::new("born").required(true) .args(["age", "year"]),
))]
struct Args {
    /// 年龄
    #[arg(short, long,value_parser = clap::value_parser!(u8))]
    age: Option<u8>,

    /// 出生年
    #[arg(short, long,value_parser = clap::value_parser!(i32))]
    year: Option<i32>,
}

fn main() {
    let args = Args::parse();

    if let Some(param) = args.age {
        println!("年龄是:{}", param);
        let year = Local::now().year();
        println!("出生年是:{}", year - param as i32);
    } else {
        let year = args.year.unwrap();
        println!("年龄是:{}", Local::now().year() - year);
        println!("出生年是:{}", year);
    }
}

查看帮助

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

Usage: game <--age <AGE>|--year <YEAR>>

Options:
  -a, --age <AGE>    年龄
  -y, --year <YEAR>  出生年
  -h, --help         Print help information
  -V, --version      Print version information

使用

root@jiangbo12490:~/git/game# cargo run -- -a 44
    Finished dev [unoptimized + debuginfo] target(s) in 0.02s
     Running `target/debug/game -a 44`
年龄是:44
出生年是:1978
root@jiangbo12490:~/git/game# cargo run -- -y 1978
    Finished dev [unoptimized + debuginfo] target(s) in 0.02s
     Running `target/debug/game -y 1978`
年龄是:44
出生年是:1978

总结

使用注解来定义了关联的参数。

附录

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