golang check if cli integer flag exists

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

golang check if cli integer flag exists

问题

我能够看到一个布尔值的标志是否存在。我正在尝试找出如何判断一个整数类型的标志是否存在,如果存在则使用该值,如果不存在则忽略。

例如,下面的代码在使用布尔标志时会执行某些操作。但是,我想为-month设置一个标志,比如go run appname.go -month=01,然后保存值为01,但如果没有使用-month,则应该像布尔标志一样忽略。在下面的代码中,我通过将默认值设置为0来解决这个问题,这样如果没有使用-month标志,值就是0。有没有更好的方法来做到这一点?

package main

import (
	"flag"
	"fmt"
	"time"
)

func main() {
	//添加标志
	useCron := flag.Bool("cron", false, "-cron,使用cron标志,默认为true")
	useNow := flag.Bool("now", false, "-now,使用cron标志,默认为true")
	useMonth := flag.Int("month", 0, "-month,指定一个月份")
	flag.Parse()

	//如果使用了-cron标志
	if *useCron {
		fmt.Printf("使用cron运行设置为日期")
		return
	} else if *useNow {
		fmt.Printf("使用当前日期")
		return
	}

	if *useMonth != 0 {
		fmt.Printf("月份:%v\n", *useMonth)
	}
}
英文:

I'm able to see if a flag exists when its a bool. I'm trying to figure out how to see if a flag exits if its integer, if it does exist use the value if not ignore.

For example, the code below does something if either Bool flags are used. BUT I want to set a flag for -month ie go run appname.go -month=01 should then save the value of 01 but if -month is not used then it should be ignored like a bool flag. In the code below I got around this by making a default value of 0 so if no -month flag is used the value is 0. Is there a better way to do this?

package main

import (
	"flag"
	"fmt"
	"time"
)

func main() {
	//Adding flags
	useCron := flag.Bool("cron", false, "-cron, uses cron flags and defaults to true")
	useNow := flag.Bool("now", false, "-now, uses cron flags and defaults to true")
	useMonth := flag.Int("month", 0, "-month, specify a month")
	flag.Parse()

	//If -cron flag is used
	if *useCron {
		fmt.Printf("Cron set using cron run as date")
		return
	} else if *useNow {
		fmt.Printf("Use Current date")
		return
	}

	if *useMonth != 0 {
	    fmt.Printf("month %v\n", *useMonth)
    }
}

答案1

得分: 1

请参阅flag.Value接口的文档和示例:

您可以定义一个实现了flag.Value接口的自定义类型,例如:

type CliInt struct {
	IsSet bool
	Val   int
}

func (i *CliInt) String() string {
	if !i.IsSet {
		return "<not set>"
	}
	return strconv.Itoa(i.Val)
}

func (i *CliInt) Set(value string) error {
	v, err := strconv.Atoi(value)
	if err != nil {
		return err
	}

	i.IsSet = true
	i.Val = v
	return nil
}

然后使用flag.Var()进行绑定:

flag.Var(&i1, "i1", "1st int to parse")
flag.Var(&i2, "i2", "2nd int to parse")

在调用flag.Parse()之后,您可以检查.IsSet标志以查看该标志是否已设置。

playground


另一种方法是在调用flag.Parse()之后调用flag.Visit()

var isSet1, isSet2 bool

i1 := flag.Int("i1", 0, "1st int to parse")
i2 := flag.Int("i2", 0, "2nd int to parse")

flag.Parse([]string{"-i1=123"})

// flag.Visit只会访问已显式设置的标志:
flag.Visit(func(fl *flag.Flag) {
	if fl.Name == "i1" {
		isSet1 = true
	}
	if fl.Name == "i2" {
		isSet2 = true
	}
})

playground

英文:

See the documentation and example for the flag.Value interface :

You may define a custom type, which implements flag.Value, for example :

type CliInt struct {
	IsSet bool
	Val   int
}

func (i *CliInt) String() string {
	if !i.IsSet {
		return &quot;&lt;not set&gt;&quot;
	}
	return strconv.Itoa(i.Val)
}

func (i *CliInt) Set(value string) error {
	v, err := strconv.Atoi(value)
	if err != nil {
		return err
	}

	i.IsSet = true
	i.Val = v
	return nil
}

and then use flag.Var() to bind it :

	flag.Var(&amp;i1, &quot;i1&quot;, &quot;1st int to parse&quot;)
	flag.Var(&amp;i2, &quot;i2&quot;, &quot;2nd int to parse&quot;)

after calling flag.Parse(), you may check the .IsSet flag to see if that flag was set.

playground


Another way is to call flag.Visit() after calling flag.Parse() :

	var isSet1, isSet2 bool

	i1 := flag.Int(&quot;i1&quot;, 0, &quot;1st int to parse&quot;)
	i2 := flag.Int(&quot;i2&quot;, 0, &quot;2nd int to parse&quot;)

	flag.Parse([]string{&quot;-i1=123&quot;})

	// flag.Visit will only visit flags which have been explicitly set :
	flag.Visit(func(fl *flag.Flag) {
		if fl.Name == &quot;i1&quot; {
			isSet1 = true
		}
		if fl.Name == &quot;i2&quot; {
			isSet2 = true
		}
	})

playground

答案2

得分: 0

在布尔标志中,你不能检查是否存在,因为你正在检查默认的false值。如果你将其更改为true,你将始终得到它存在的结果。

useCron := flag.Bool("cron", true, "-cron,使用cron标志,默认为true")
useNow := flag.Bool("now", true, "-now,使用cron标志,默认为true")

对于任何其他数据类型也是如此,我们只能检查默认值。

你可以使用flag.NFlag()函数。该函数返回由命令行界面设置的标志的数量。当所有选项都是必需的时,这个选项是有意义的。

@LeGEC的答案满足了你的要求。

英文:

In the bool flag also you can't check if exist or not because you are checking the default false value. If you will change it to true you will always get it as exists.

useCron := flag.Bool(&quot;cron&quot;, true, &quot;-cron, uses cron flags and defaults to true&quot;)
useNow := flag.Bool(&quot;now&quot;, true, &quot;-now, uses cron flags and defaults to true&quot;)

The same goes for any other data type, we can only check the default values.

You can use flag.NFlag().
This function returns a number of flags set by the CLI.
This option makes sense when all the options are required.

@LeGEC answer fulfills your requirement.

huangapple
  • 本文由 发表于 2022年2月25日 11:43:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/71260782.html
匿名

发表评论

匿名网友

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

确定