Clap 命令行解析
学习目标
- 掌握 derive 方式定义 CLI
- 掌握子命令
- 理解参数验证
核心概念
基本用法
[dependencies]
clap = { version = "4", features = ["derive"] }
use clap::Parser;
#[derive(Parser, Debug)]
#[command(name = "mycli")]
#[command(about = "A simple CLI tool")]
struct Args {
#[arg(short, long)]
name: String,
#[arg(short, long, default_value_t = 1)]
count: u32,
#[arg(short, long)]
verbose: bool,
}
fn main() {
let args = Args::parse();
for _ in 0..args.count {
println!("Hello, {}!", args.name);
}
if args.verbose {
println!("详细模式已启用");
}
}
子命令
use clap::{Parser, Subcommand};
#[derive(Parser)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
Add {
description: String,
},
List {
#[arg(long)]
all: bool,
},
Remove {
id: u32,
},
}
fn main() {
let cli = Cli::parse();
match cli.command {
Commands::Add { description } => {
println!("添加任务: {}", description);
}
Commands::List { all } => {
println!("列出任务 (all={})", all);
}
Commands::Remove { id } => {
println!("删除任务: {}", id);
}
}
}
参数验证
use clap::Parser;
#[derive(Parser)]
struct Args {
#[arg(long, value_parser = clap::value_parser!(u16).range(1024..))]
port: u16,
#[arg(long, value_parser = ["debug", "info", "warn", "error"])]
log_level: String,
}
小结
| 语法 | 用途 |
|---|
#[derive(Parser)] | 自动解析命令行 |
#[arg(short, long)] | 参数选项 |
#[command(subcommand)] | 子命令 |
default_value_t | 默认值 |
value_parser | 参数验证 |