试试 structopt

193 阅读1分钟

简介

structoptclap功能上类似,主要用于命令行参数的处理。

structopt基于 clap 库构建,提供了更高级的抽象,使得定义命令行参数的代码更加简洁和直观。structopt 通过 Rust 的自定义派生(derive)宏来自动生成命令行参数解析逻辑.

主要特点

  1. 基于宏的声明式 API:使用 Rust 的 derive 宏和属性注解,可以在结构体和枚举上定义命令行参数,简化了代码编写。
  2. clap 深度集成structopt 通过 clap 库实现底层功能,继承了 clap 的强大功能和灵活性。
  3. 自动生成帮助和版本信息structopt 可以根据结构体和枚举的定义自动生成命令行工具的帮助和版本信息。
  4. 类型安全:通过结构体字段的类型,structopt 自动进行类型转换,确保命令行参数的类型安全。

代码修改

整体修改还是比较容易的的

  • #[derive(Debug, Parser)]中的Parser换成StructOpt
  • 然后所有的commandarg换成structopt即可

修改后的代码如下:

use structopt::StructOpt;

#[derive(Debug, StructOpt)]
#[structopt(name = "rcli", author, about, long_about = "")]
struct Opts {
    #[structopt(subcommand)]
    cmd: SubCommand,
}

#[derive(Debug, StructOpt)]
enum SubCommand {
    #[structopt(name = "csv", about = "Show SCV, or convert CSV to other formats")]
    Csv(CsvOpts),
}

#[derive(Debug, StructOpt)]
struct CsvOpts {
    #[structopt(short, long)]
    input: String,

    #[structopt(short, long, default_value = "output.json")]
    output: String,

    #[structopt(short, long, default_value = ",")]
    delimiter: char,

    #[structopt(long)]
    header: bool,
}

fn main() {
    let opts = Opts::from_args();
    print!("{:?}", opts)
}

总结

本文主要基于上篇文章,尝试了下structopt。整体比较容易上手,但structopt 是一个基于 clap 的 Rust 库。其实如果需要处理非常复杂的命令行解析需求,可以直接使用 clap 提供的更底层和细粒度的控制。