How to create and parse flag arrays and slices in Go?

To create and parse flag arrays and slices in Go, you can utilize the flag package provided by the standard library.

Here's an example of how you can create and parse flag arrays and slices in Go:

  1. Import the necessary packages:

    import ( "flag" "fmt" "strings" )
  2. Define the command-line flags:

    // For array of strings var arrayFlag = flag.String("array", "", "comma-separated list of values") // For slice of strings type stringSlice []string func (s *stringSlice) String() string { return strings.Join(*s, ",") } func (s *stringSlice) Set(value string) error { *s = append(*s, strings.Split(value, ",")...) return nil } var sliceFlag stringSlice
  3. Parse the command-line flags:

    flag.Parse()
  4. Access the parsed flag values:

    // Array arrayValues := strings.Split(*arrayFlag, ",") fmt.Println("Array Values:", arrayValues) // Slice sliceValues := sliceFlag fmt.Println("Slice Values:", sliceValues)

Here's a full example demonstrating the usage of array and slice flags:

package main import ( "flag" "fmt" "strings" ) // For array of strings var arrayFlag = flag.String("array", "", "comma-separated list of values") // For slice of strings type stringSlice []string func (s *stringSlice) String() string { return strings.Join(*s, ",") } func (s *stringSlice) Set(value string) error { *s = append(*s, strings.Split(value, ",")...) return nil } var sliceFlag stringSlice func main() { flag.Var(&sliceFlag, "slice", "comma-separated list of values") flag.Parse() // Array arrayValues := strings.Split(*arrayFlag, ",") fmt.Println("Array Values:", arrayValues) // Slice sliceValues := sliceFlag fmt.Println("Slice Values:", sliceValues) }

Now, you can compile and run the code by passing the desired array and slice flags:

$ go run main.go -array=value1,value2,value3 -slice=value4,value5,value6 Array Values: [value1 value2 value3] Slice Values: [value4 value5 value6]

This way, you can create and parse flag arrays and slices in Go using the flag package.