Getting a List of Values into a Flag in Go
In Go, the flag package supports parsing command-line arguments. However, it initially provided only a limited range of data types (String, Int, Bool). To accommodate more complex data, you can define your own flag type and use flag.Var() to bind it.
Custom Flag Type for List
Consider a flag that accepts multiple values as a list. First, define a custom flag type:
type arrayFlags []string // String is an implementation of the flag.Value interface func (i *arrayFlags) String() string { return fmt.Sprintf("%v", *i) } // Set is an implementation of the flag.Value interface func (i *arrayFlags) Set(value string) error { *i = append(*i, value) return nil }
Using the Custom Flag
Next, declare a variable of this type to bind with the custom flag:
var myFlags arrayFlags
Registering the Custom Flag
Finally, you can register your custom flag with the flag package:
flag.Var(&myFlags, "list1", "Some description for this param.")
Now, you can pass multiple values to this flag when running your program:
go run your_file.go --list1 value1 --list1 value2
Updated Code Snippet
For reference, here is the complete code snippet:
package main import ( "flag" "fmt" ) type arrayFlags []string // String is an implementation of the flag.Value interface func (i *arrayFlags) String() string { return fmt.Sprintf("%v", *i) } // Set is an implementation of the flag.Value interface func (i *arrayFlags) Set(value string) error { *i = append(*i, value) return nil } var myFlags arrayFlags func main() { flag.Var(&myFlags, "list1", "Some description for this param.") flag.Parse() }
The above is the detailed content of How to Define a Custom Flag Type for a List of Values in Go?. For more information, please follow other related articles on the PHP Chinese website!