incremental integer with flag (or other) package in go?

huangapple go评论97阅读模式
英文:

incremental integer with flag (or other) package in go?

问题

一些Unix工具允许通过多次使用-v命令行开关来设置详细程度。因此,-v表示1,-vv-v -v表示2。在我所熟悉的Perl中,可以通过Getopt::Long实现这一点,代码如下:GetOptions ('verbose+' => \$verbose);

作为一个Go的新手,我还没有找到如何实现这一点。目前我找到的唯一选项是使用带有整数值的-v,例如-v 2

更新:我现在决定使用一个非标准库,因为它看起来非常方便使用。你可以在这里找到它:https://cli.urfave.org/v2/getting-started/

英文:

Some unix tools allow to set the verbosity level by giving the -v commandline switch several times. So -v would be 1, -vv or -v -v would be 2. Perl, where I come from, has this in Getopt::Long like this: GetOptions ('verbose+' => \$verbose);.

As a go newbie, I couldn't yet figure out how to achieve this. The only option I found yet is, to use -v with an integer value so -v 2.

Update: I've now decided to use a non-standard library as it seems very convenient to use. https://cli.urfave.org/v2/getting-started/

答案1

得分: 3

go的flag包不使用GNU风格选项,因此它不区分能够组合短选项的短选项和长选项。如果你想使用-v-vv-vvv,你需要为它们指定独立的标志(实际上很多程序都是这样做的),或者使用非标准的标志包。

你可以通过实现flag.Value接口来创建一个在多次调用中递增的标志值。通过实现IsBoolFlag,你还可以进一步指示解析器不将后面的参数包含为要设置的标志值,并使-v等效于-v=true

type incrementor int

func (i incrementor) String() string {
	return strconv.Itoa(int(i))
}

func (incrementor) IsBoolFlag() bool {
	return true
}

func (i *incrementor) Set(string) error {
	(*i)++
	return nil
}

https://go.dev/play/p/2HPfVng-a8J

英文:

The go flag package does not use GNU-style options, so it does not differentiate between short and long options with the ability to combine short options. If you want to use -v, -vv, -vvv you will need to specify independent flags for these (which a lot of programs actually do), or use a non-standard flag package.

You can make a flag value which increments with multiple invocations by implementing the flag.Value interface. By also implementing IsBoolFlag you can further instruct the parser to not include the following argument as the flag value to set, and makes -v equivalent to -v=true.

type incrementor int

func (i incrementor) String() string {
	return strconv.Itoa(int(i))
}

func (incrementor) IsBoolFlag() bool {
	return true
}

func (i *incrementor) Set(string) error {
	(*i)++
	return nil
}

https://go.dev/play/p/2HPfVng-a8J

huangapple
  • 本文由 发表于 2023年7月12日 18:48:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76669747.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定