You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在clap_derive中重命名子命令占位符<COMMAND>?

如何在clap_derive中重命名子命令的占位符

要修改子命令的占位符显示,你需要给子命令字段添加placeholder参数——name参数仅用于设置内部参数标识,不会影响帮助信息里的占位符文本。

修改后的代码

调整src/main.rs中Args结构体的action字段定义:

use clap::{Parser, Subcommand};

#[derive(Debug, Parser)]
#[command(author, version, about, long_about = "Frobnicate the fizzbuzz")]
struct Args {
    #[arg(index = 1, name = "xml_file", help = "The base XML file to operate on")]
    file: String,
    #[command(subcommand)]
    #[arg(placeholder = "action")]
    action: Action,
}

#[derive(Clone, Debug, Subcommand)]
pub enum Action {
    #[command(long_about = "Add a new type")]
    Add,
    #[command(long_about = "Display the selected type's properties")]
    Find,
}

fn main() {
    Args::parse();
}

验证效果

重新编译运行后,帮助信息的Usage部分会显示预期的占位符:

〉cargo run
   Compiling clap_test_subcommand_placeholder v0.1.0 (/home/rne/clap_test_subcommand_placeholder)
    Finished dev [unoptimized + debuginfo] target(s) in 0.62s
     Running `target/debug/clap_test_subcommand_placeholder`
Usage: clap_test_subcommand_placeholder <xml_file> <action>

Commands:
  add   Add a new type
  find  Display the selected type's properties
  help  Print this message or the help of the given subcommand(s)

Arguments:
  <xml_file>  The base XML file to operate on

Options:
  -h, --help     Print help (see more with '--help')
  -V, --version  Print version

关键说明

  • name = "action"仅作用于clap内部的参数命名逻辑,不会改变对外显示的占位符。
  • #[arg(placeholder = "action")]是专门用于自定义Usage中占位符文本的属性。

内容的提问来源于stack exchange,提问作者user3515670

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 15:46:14