clap教程:第1章

文章介绍了如何使用Rust的clap库通过derivemacro创建自定义命令行解析器,包括设置版本信息、帮助文本以及从Cargo.toml获取元数据。还展示了如何改变命令行为,如添加下一行帮助选项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

配置解析器

clap 可以使用 deriveParser 来开始构建解析器。

use clap::Parser;

#[derive(Parser)]
#[command(name = "MyApp")]
#[command(version = "1.0")]
#[command(about = "Does awesome things", long_about = None)]
struct Cli {
    #[arg(long)]
    two: String,
    #[arg(long)]
    one: String,
}

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

    println!("two: {:?}", cli.two);
    println!("one: {:?}", cli.one);
}
$ 02_apps_derive --help
Does awesome things

Usage: 02_apps_derive[EXE] --two <TWO> --one <ONE>

Options:
      --two <TWO>  
      --one <ONE>  
  -h, --help       Print help
  -V, --version    Print version

$ 02_apps_derive --version
MyApp 1.0

还可以在结构体上使用 #[command(version, about)] 属性默认值来填充来自 Cargo.toml 文件的相关字段。

use clap::Parser;

#[derive(Parser)]
#[command(version, about, long_about = None)] // 从 `Cargo.toml` 读取
struct Cli {
    #[arg(long)]
    two: String,
    #[arg(long)]
    one: String,
}

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

    println!("two: {:?}", cli.two);
    println!("one: {:?}", cli.one);
}
$ 02_crate_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 02_crate_derive[EXE] --two <TWO> --one <ONE>

Options:
      --two <TWO>  
      --one <ONE>  
  -h, --help       Print help
  -V, --version    Print version

$ 02_crate_derive --version
clap [..]

在结构体上使用 #[command] 属性可以更改 clap 的应用行为。任何 Command 构建器函数都可以用作属性,例如 Command::next_line_help

use clap::Parser;

#[derive(Parser)]
#[command(version, about, long_about = None)]
#[command(next_line_help = true)]
struct Cli {
    #[arg(long)]
    two: String,
    #[arg(long)]
    one: String,
}

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

    println!("two: {:?}", cli.two);
    println!("one: {:?}", cli.one);
}
$ 02_app_settings_derive --help
A simple to use, efficient, and full-featured Command Line Argument Parser

Usage: 02_app_settings_derive[EXE] --two <TWO> --one <ONE>

Options:
      --two <TWO>
          
      --one <ONE>
          
  -h, --help
          Print help
  -V, --version
          Print version
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值