Skip to content

Instantly share code, notes, and snippets.

@sillyfellow
Last active June 2, 2020 07:44
Show Gist options
  • Save sillyfellow/2e3819fd09a3c9252907182c6ae8d5c7 to your computer and use it in GitHub Desktop.
Save sillyfellow/2e3819fd09a3c9252907182c6ae8d5c7 to your computer and use it in GitHub Desktop.
An example for providing multiple values to the same command line parameter - with builtin `flag` in Go
// Package main shows an example for providing multiple values to the same
// command line parameter - with builtin `flag` in Go.
package main
import (
"flag"
"fmt"
"strings"
)
// Create a type
type multiValue []string
// On which the interface Stringer is implemented
func (values *multiValue) String() string {
return strings.Join([]string(*values), "\n")
}
// Also the method Set must be implemented
func (values *multiValue) Set(value string) error {
*values = append(*values, value)
return nil
}
// Then the usage is like this.
// Use `flag.Var` as the type, then each value will be in the slice.
func main() {
var multiFlag multiValue
flag.Var(&multiFlag, "value", "provide one by one: `--value value1 --value \"value with whitespace in\"`")
flag.Parse()
fmt.Println(&multiFlag)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment