简体   繁体   English

在 clap 中使用结构作为命令行参数

[英]Using a structure as a command line argument in clap

Trying to use a struct within a struct in clap :尝试在clap的结构中使用结构:

use clap::{Args, Parser};
use std::path::PathBuf;

#[derive(Parser, Debug)]
enum Command {
    Foo(Foo),
}

#[derive(Args, Debug)]
struct Foo {
    bar: Option<Bar>,

    path: PathBuf,
}

#[derive(Parser, Clone, Debug)]
struct Bar {
    bla: u8,

    bla_2: String,
}

fn main() {
    let cli = Command::parse();
    println!("cli {:#?}", cli);
}

So I could call the app with the following options: cargo run -- foo bar 42 baz /tmp/a or just cargo run -- foo /tmp/a since the bar argument is optional.所以我可以使用以下选项调用应用程序: cargo run -- foo bar 42 baz /tmp/a或只是cargo run -- foo /tmp/a因为bar参数是可选的。

However, currently it does not build:但是,目前它没有构建:

  --> src/main.rs:11:5
   |
11 |     bar: Option<Bar>,
   |     ^^^ the trait `FromStr` is not implemented for `Bar`
   |

And since the values within Bar have to be space-separated implementing a FromStr would not do the trick anyway.而且由于Bar中的值必须以空格分隔,因此实现FromStr都不会成功。

Is it even possible to do something of this fashion in clap currently?目前甚至有可能在clap中做这种时尚的事情吗?

There are several problems with your code.您的代码有几个问题。 The biggest one is:最大的一个是:

  • An optional positional item can never come before a required positional argument一个可选的位置项永远不能出现一个必需的位置参数之前

This is a problem in your case because your command line looks like this:在您的情况下这是一个问题,因为您的命令行如下所示:

cargo run -- <required> [optional] /tmp/a

If you have a required path at the end, there can not be an optional positional argument before that.如果最后有一个必需的路径,则在此之前不能有可选的位置参数。

Further problems:进一步的问题:

  • #[derive(Parser)] should be attached to a struct , not an enum . #[derive(Parser)]应该附加到struct ,而不是enum
  • There should only be one #[derive(Parser)] , which represents the entry object of your arguments parser.应该只有一个#[derive(Parser)] ,它代表参数解析器的入口对象。

I'm unsure how else to help you, except pointing out your problems.除了指出你的问题,我不确定还能如何帮助你。 If the invocations cargo run -- foo bar 42 baz /tmp/a and cargo run -- foo /tmp/a are non-negotiable, I don't think clap is the right library for you;如果调用cargo run -- foo bar 42 baz /tmp/acargo run -- foo /tmp/a是不可协商的,我认为clap不适合你; I think you should parse by hand.我认为您应该手动解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM