如何使用clap-derive在Rust程序的--help界面末尾添加自定义帮助消息?
使用Clap-derive在帮助界面底部添加自定义消息
当然可以实现,你只需要借助Clap-derive中#[command]属性的after_help参数,就能在所有参数标志描述之后、帮助界面的末尾插入自定义文本。
修改你的示例代码如下:
use clap::Parser; use std::path::PathBuf; #[derive(Parser, Debug, Default)] #[command(about, version, after_help = "Some very long explanation that should be printed at the end of the help screen")] pub struct Args { /// Path to a file. #[arg(short, long)] pub file: Option<PathBuf>, } fn main() { let _args = Args::parse(); }
如果你的自定义消息内容较长、需要换行,可以用Rust的原始字符串(r#"..."#)来定义:
#[derive(Parser, Debug, Default)] #[command( about, version, after_help = r#" Some very long explanation that should be printed at the end of the help screen 这是第二行自定义内容,支持多行展示 "# )] pub struct Args { /// Path to a file. #[arg(short, long)] pub file: Option<PathBuf>, }
运行程序并执行--help参数后,输出会符合你的预期:
MyProgram ... --file FILE Path to a file Some very long explanation that should be printed at the end of the help screen
内容的提问来源于stack exchange,提问作者Yuri Astrakhan
相关产品推荐
相关产品推荐

