首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用structopt创建嵌套子命令?

如何使用structopt创建嵌套子命令?
EN

Stack Overflow用户
提问于 2022-01-12 21:02:43
回答 1查看 231关注 0票数 2

引言

我目前有使用structopt的子命令,类似于另一个answer。但是,我希望有类似于docker工作方式的嵌套子命令:

代码语言:javascript
复制
docker image ls
docker image pull

当前代码

main.rs

代码语言:javascript
复制
mod cli;

use structopt::StructOpt;
use crate::cli::{Opt, Command};

fn main() {

    let opt = Opt::from_args();
    match opt.cmd {
        Command::Subcommand { .. } => {
            // Do something
        }
    }

}

cli/mod.rs

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

#[derive(StructOpt, Debug)]
pub enum Command {
    Subcommand {
       // args
    }
}

#[derive(StructOpt, Debug)]
pub struct Opt {
    #[structopt(subcommand)]
    pub cmd: Command,
}

我试过的

添加了另一个结构: main.rs

代码语言:javascript
复制
mod cli;

use structopt::StructOpt;
use crate::cli::{Opt, Resource};

fn main() {

    let opt = Opt::from_args();
    match opt.resource {
        Resource::Command { .. } => {
            // do something
        }
    }

}

cli/mod.rs

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

#[derive(StructOpt, Debug)]
pub enum Command {
    Subcommand {
        // args
    }
}

#[derive(StructOpt, Debug)]
pub struct Resource {
    #[structopt(subcommand)]
    image: Image
}

#[derive(StructOpt, Debug)]
pub struct Opt {
    #[structopt(subcommand)]
    pub resource: Resource,
}

但是,我得到了以下错误:

代码语言:javascript
复制
help: use fully-qualified syntax: `<Resource as Trait>::ImageCommand
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-01-12 22:05:21

由于命令被描述为枚举,所以子命令将是“sub”(枚举变体中的enum )。在下面的示例中,ImageCommand是命令枚举变体中的枚举:

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

#[derive(StructOpt, Debug)]
pub struct ImagePullOptions {
    pub name: String,
}

#[derive(StructOpt, Debug)]
pub enum ImageCommand {
    #[structopt(name = "ls")]
    List,
    Pull(ImagePullOptions),
}

#[derive(StructOpt, Debug)]
pub enum Command {
    Image(ImageCommand),
}

#[derive(StructOpt, Debug)]
pub struct Options {
    #[structopt(subcommand)]
    pub command: Command,
}

fn main() {
    let options: Options = Options::from_args();
    match options.command {
        Command::Image(image_command) => {
            match image_command {
                ImageCommand::List => println!("listing..."),
                ImageCommand::Pull(pull_options) => println!("pulling {}...", pull_options.name),
            }
        }
    }
}

试验用:

代码语言:javascript
复制
$ cargo run -- image 

USAGE:
    testsubopt image <SUBCOMMAND>

FLAGS:
    -h, --help       Prints help information
    -V, --version    Prints version information

SUBCOMMANDS:
    help    Prints this message or the help of the given subcommand(s)
    ls      
    pull    
代码语言:javascript
复制
$ cargo run -- image pull asd
pulling asd...
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70688380

复制
相关文章

相似问题

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