gpt4 book ai didi

rust - 如何在带有 structopt crate 的子命令后使用 CLI 参数?

转载 作者:行者123 更新时间:2023-12-03 11:30:16 28 4
gpt4 key购买 nike

例如,使用

运行我的应用程序
./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"

最佳答案

根据 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);
}

请注意,全局参数必须是可选的或具有默认值。

关于rust - 如何在带有 structopt crate 的子命令后使用 CLI 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59868058/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com