如何使用 clap 和 derive 创建默认子命令

Rou*_*mbe 29 rust clap

如果用户没有提供任何参数,我试图启动一个子命令,但我找不到任何方法来执行此操作。

如果没有提供子命令,当我想要传递一些操作时,将显示帮助。

Fin*_*nis 37

基于官方clap 文档

通过将子命令包装在 中进行修改Option,使其成为可选:

use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(author, version, about, long_about = None)]
#[command(propagate_version = true)]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Adds files to myapp
    Add { name: Option<String> },
}

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

    // You can check for the existence of subcommands, and if found use their
    // matches just as you would the top level cmd
    match &cli.command {
        Some(Commands::Add { name }) => {
            println!("'myapp add' was used, name is: {:?}", name)
        }
        None => {
            println!("Default subcommand");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)