rust - 如何使用代表 StructOpt 子命令的枚举?

标签 rust enums arguments structopt

引用"Git" example of StructOpt ,我不明白我应该如何使用参数中的数据。

我对 Rust 还很陌生,所以我猜这很明显。不幸的是,我能找到的所有枚举示例都只在对象上执行 println!,所以我被卡住了。我想我会做一个匹配,但它不起作用。

然后您将如何找到用户传递了哪些命令来运行您的程序?

#[macro_use]
extern crate structopt;

use std::path::PathBuf;
use structopt::StructOpt;

#[derive(StructOpt, Debug)]
#[structopt(name = "git", about = "the stupid content tracker")]
enum Git {
    #[structopt(name = "add")]
    Add {
        #[structopt(short = "i")]
        interactive: bool,
        #[structopt(short = "p")]
        patch: bool,
        #[structopt(parse(from_os_str))]
        files: Vec<PathBuf>
    },
    #[structopt(name = "fetch")]
    Fetch {
        #[structopt(long = "dry-run")]
        dry_run: bool,
        #[structopt(long = "all")]
        all: bool,
        repository: Option<String>
    },
    #[structopt(name = "commit")]
    Commit {
        #[structopt(short = "m")]
        message: Option<String>,
        #[structopt(short = "a")]
        all: bool
    }
}

fn main() {
    let opt = Git::from_args();
    println!("{:?}", opt);

    match opt() {
        Git::Add(cmd) => println!("{:?}", cmd.interactive),
        _ => (),
    }
}

编译:

05:42 $ cargo run -- add -i
   Compiling example v0.1.0 (file:///Users/froyer/src/example)
error[E0532]: expected tuple struct/variant, found struct variant `Git::Add`
  --> src/main.rs:41:9
   |
41 |         Git::Add(cmd) => println!("{:?}", cmd.interactive),
   |         ^^^^^^^^ did you mean `Git::Add { /* fields */ }`?

error[E0618]: expected function, found enum variant `opt`
  --> src/main.rs:40:11
   |
37 |     let opt = Git::from_args();
   |         --- `opt` defined here
...
40 |     match opt() {
   |           ^^^^^ not a function
help: `opt` is a unit variant, you need to write it without the parenthesis
   |
40 |     match opt {
   |           ^^^

最佳答案

感谢issue #1 in the structopt repository ,我终于明白它应该如何工作了:)

fn main () {
    match Git::from_args() {
        Git::Add { interactive, patch, files } => {
            println!("{:?}", interactive)
        },
        Git::Commit { message, all } => {
            //...
        }
        _ => (),
    }
}

关于rust - 如何使用代表 StructOpt 子命令的枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50673567/

相关文章:

rust - 如何从嵌套迭代器中收集数据?

rust - 向量(或迭代器)的 bool 掩码

python - 如何在python中将int转换为Enum?

c# - 表达式树库和枚举之间的关系

C: switch 中需要整数表达式而不是 XY

python - selenium.webdriver.firefox.options - 它是关于什么的?

rust - 为什么不安全的代码可以编译,但推送到向量的类似代码会提示引用的生命周期不够长?

multithreading - 我可以安全地对不应该是多线程的东西进行多线程处理吗?

c++ - 使用指针传递 C 字符串参数

c - 参数类型错误