命令行工具开发 #

一、使用clap #

rust
use clap::Parser;

#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args {
    #[arg(short, long)]
    name: String,
    
    #[arg(short, long, default_value_t = 1)]
    count: u8,
}

fn main() {
    let args = Args::parse();
    
    for _ in 0..args.count {
        println!("Hello {}!", args.name);
    }
}

二、子命令 #

rust
use clap::{Parser, Subcommand};

#[derive(Parser)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    Add { name: String },
    List,
}

fn main() {
    let cli = Cli::parse();
    
    match cli.command {
        Commands::Add { name } => println!("添加: {}", name),
        Commands::List => println!("列出所有"),
    }
}

三、总结 #

本章学习了:

  • clap 基本使用
  • 参数定义
  • 子命令
最后更新:2026-03-27