ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

0263-CLAP-注解定义子命令

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 -- -hCompiling game v1.0.0 (/root/git/game)Finished dev [unoptimized + debuginfo] target(s) in 0.48sRunning `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.01sRunning `target/debug/game add '张三'`
姓名是:张三
年龄是:None
root@jiangbo12490:~/git/game# cargo run -- add 张三 44Finished dev [unoptimized + debuginfo] target(s) in 0.01sRunning `target/debug/game add '张三' 44`
姓名是:张三
年龄是:Some(44)

总结

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

附录

返回列表