Golang 一个 flag 参数获取多个值
flag包提供一个动态Value接口,标准库中的flag方法都是通过Value实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// Value is the interface to the dynamic value stored in a flag.
// (The default value is represented as a string.)
//
// If a Value has an IsBoolFlag() bool method returning true,
// the command-line parser makes -name equivalent to -name=true
// rather than using the next command-line argument.
//
// Set is called once, in command line order, for each flag present.
// The flag package may call the String method with a zero-valued receiver,
// such as a nil pointer.
type Value interface {
String() string
Set(string) error
}
|
实现方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
type argFlags []string
func (a *argFlags) Set(s string) error {
*a = append(*a, s)
return nil
}
func (a *argFlags) String() string {
return strings.Join(*a, " ")
}
var args argFlags
func main() {
flag.Var(&args, "args", "command line arguments")
flag.Parse()
fmt.Printf("%+v", args)
}
|
执行传入参数
1
|
$ ./main --args foo --args bar
|
参考