0263-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, Subcommand};

/// 命令行参数
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// 添加人员信息
    Add {
        /// 姓名
        name: String,

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

fn main() {
    let cli = Cli::parse();

    match &cli.command {
        Commands::Add { name, age } => {
            println!("姓名是:{}", name);
            println!("年龄是:{:?}", age);
        }
    }
}

查看帮助

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

Usage: game <COMMAND>

Commands:
  add   添加人员信息
  help  Print this message or the help of the given subcommand(s)

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

使用

root@jiangbo12490:~/git/game# cargo run -- add 张三
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/game add '张三'`
姓名是:张三
年龄是:None
root@jiangbo12490:~/git/game# cargo run -- add 张三 44
    Finished dev [unoptimized + debuginfo] target(s) in 0.01s
     Running `target/debug/game add '张三' 44`
姓名是:张三
年龄是:Some(44)

总结

使用注解来定义了子命令。

附录

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