Golang标志:忽略丢失的标志并解析多个重复的标志

mat*_*att 3 go go-flag

我是Golang的新手,我无法使用flag找到解决此问题的方法。

我如何使用标志,以便我的程序可以处理此类调用,其中-term标志的出现次数可能是可变的,包括0次:

./myprogram -f flag1
./myprogram -f flag1 -term t1 -term t2 -term  t3
Run Code Online (Sandbox Code Playgroud)

ret*_*oot 7

您需要声明自己的类型,该类型实现Value接口。这是一个例子。

// Created so that multiple inputs can be accecpted
type arrayFlags []string

func (i *arrayFlags) String() string {
    // change this, this is just can example to satisfy the interface
    return "my string representation"
}

func (i *arrayFlags) Set(value string) error {
    *i = append(*i, strings.TrimSpace(value))
    return nil
}
Run Code Online (Sandbox Code Playgroud)

然后在主函数中解析标志

var myFlags arrayFlags

flag.Var(&myFlags, "term", "my terms")
flag.Parse()
Run Code Online (Sandbox Code Playgroud)

现在所有的术语都包含在切片中 myFlags