首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何创建一个StructOpt命令,其中所有子组件都是可选的

如何创建一个StructOpt命令,其中所有子组件都是可选的
EN

Stack Overflow用户
提问于 2021-01-15 06:34:45
回答 1查看 674关注 0票数 1

我想安排如下的子命令:

  • mycmd status:打印一个短状态-不工作
  • mycmd status full:打印详细状态-好的
  • mycmd status dump:将完全调试状态转储到文件- OK

我无法实现简单的mycmd status,因为StructOpt认为我缺少了一个所需的子命令(子命令?)打印用法。这些文档表明,我需要以某种方式使用Option<>特性,但我不知道在这种情况下是如何使用的。

我有一件非常类似的事情:

main.rs

代码语言:javascript
复制
use structopt::StructOpt;
// ... other use cmds ...
#[derive(Debug, StructOpt)]
#[structopt(
    name = "mycmd",
    about = "A utility to do stuff."
)]
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
#[structopt(setting = structopt::clap::AppSettings::SubcommandRequired)]
struct Opts {
    #[structopt(short = "v", parse(from_occurrences))]
    /// Increase message verbosity
    verbosity: usize,
    #[structopt(subcommand)]
    cmd: Tool,
}

#[derive(Debug, StructOpt)]
enum Tool {
    #[structopt(name = "dofoo")]
    DoFoo(dofoo::Command),
    #[structopt(name = "status")]
    Status(status::Command),
}

status.rs

代码语言:javascript
复制
use structopt::StructOpt;

#[derive(Debug, StructOpt)]
#[structopt(name = "status", about = "Get the status of stuff.")]
#[structopt(setting = structopt::clap::AppSettings::ColoredHelp)]
#[structopt(max_term_width = 80)]
pub enum Command {
    #[structopt(name = "full")]
    /// Print full (i.e. verbose) status
    Full {},
    #[structopt(name = "dump")]
    /// Creates a zipped dump of the full system status to a file
    Dump {
        #[structopt(short = "o", long = "out", value_name = "FILE", parse(from_os_str))]
        /// Filename of the output file.
        out_fname: PathBuf,
    },
}

impl Command {
    pub fn execute(self) -> Result<()> {
        match self {
            Command::Full {} => cmd_do_verbose_print(),
            Command::Dump { out_fname } => cmd_do_file_dump(out_fname),
            // TODO: Bad. This is dead code.
            _ => cmd_do_print(),
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2021-01-15 06:56:10

这些文档表明,我需要以某种方式使用Option<>特性,但我不知道在这种情况下是如何使用的。

不是一种特质文档索引中的“可选子命令”中有一个例子

它只是做与您的Opts相同的事情,但是使[structopt(subcommand)]成员成为Option<T>而不是T

代码语言:javascript
复制
    #[derive(Debug, StructOpt)]
    pub struct Command {
        #[structopt(subcommand)]
        cmd: Option<Cmd>,
    }
    #[derive(Debug, StructOpt)]
    pub enum Cmd {
        /// Print full (i.e. verbose) status
        Full {},
    ...

我有一件非常类似的事情:

当你遇到问题时,一个实际的可运行的复制案例是有用的.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65731493

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档