Acquiring a List of Values as a Flag in Golang
In Golang, the standard flag package provides the ability to parse flags from the command line, but it inherently supports only primitive types such as strings, integers, and booleans. To handle a list of values as a flag, one can implement a custom flag.Value type and utilize flag.Var() for binding it.
An example implementation is available below:
import ( "flag" "fmt" ) type arrayFlags []string // String is a required implementation of the flag.Value interface func (i *arrayFlags) String() string { return fmt.Sprintf("%v", *i) } // Set is another required 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 parameter.") flag.Parse() }
This custom flag type can then be used to pass multiple flag values, such as:
go run your_file.go --list1 value1 --list1 value2
In summary, by implementing a custom flag.Value type and utilizing flag.Var(), Golang allows developers to parse a list of values as flags, providing greater flexibility in command-line argument handling.
The above is the detailed content of How to Parse a List of Values as a Flag in Golang?. For more information, please follow other related articles on the PHP Chinese website!