例如,使用运行我的应用程序
./app --foo=bar get运行良好,但是
./app get --foo=bar生成一个错误:
error: Found argument '--foo' which wasn't expected, or isn't valid in this context
USAGE:
app --foo <foo> get代码:
use structopt::*;
#[derive(Debug, StructOpt)]
#[structopt(name = "app")]
struct CliArgs {
#[structopt(long)]
foo: String,
#[structopt(subcommand)]
cmd: Cmd,
}
#[derive(Debug, StructOpt)]
enum Cmd {
Get,
Set,
}
fn main() {
let args = CliArgs::from_args();
println!("{:?}", args);
}依赖关系:
structopt = { version = "0.3", features = [ "paw" ] }
paw = "1.0"发布于 2020-01-23 05:19:03
根据issue 237的说法,有一个global参数。出乎意料的是,文档中没有提到它。
在global = true中,它工作得很好:
use structopt::*;
#[derive(Debug, StructOpt)]
#[structopt(name = "cli")]
struct CliArgs {
#[structopt(
long,
global = true,
default_value = "")]
foo: String,
#[structopt(subcommand)]
cmd: Cmd,
}
#[derive(Debug, StructOpt)]
enum Cmd {
Get,
Set,
}
fn main() {
let args = CliArgs::from_args();
println!("{:?}", args);
}请注意,全局参数必须是可选的或具有默认值。
发布于 2020-01-23 05:19:07
您需要为每个具有参数的命令枚举变量提供另一个结构:
use structopt::*; // 0.3.8
#[derive(Debug, StructOpt)]
struct CliArgs {
#[structopt(subcommand)]
cmd: Cmd,
}
#[derive(Debug, StructOpt)]
enum Cmd {
Get(GetArgs),
Set,
}
#[derive(Debug, StructOpt)]
struct GetArgs {
#[structopt(long)]
foo: String,
}
fn main() {
let args = CliArgs::from_args();
println!("{:?}", args);
}./target/debug/example get --foo=1
CliArgs { cmd: Get(GetArgs { foo: "1" }) }https://stackoverflow.com/questions/59868058
复制相似问题