Go-Lang Flags

Command-Line Flags - a common way to specify options for command-line programs

Basic flag declarations available for string, integer and boolean options

  // Declared with a name, default value and short description
  wordPtr := flag.String("word", "foo", "help message for flagname")

  numPtr := flag.Int("numb", 42, "an int")

  boolPtr := flag.Bool("fork", false, "a bool")

  // Declaring an option that uses an existing variable
  var svar string
  flag.StringVar(&svar, "svar", "bar", "a string var")

  // Execute command line parsing after all flags are declared

  // You can dump the parsed options including any trailing positional arguments
  // Dereference the pointers e.g. *wordPtr to get actual option value
  fmt.Println("word", *wordPtr)
  fmt.Println("tail", flag.Args())

To experiment, compile and run the resulting binary go build cmd.go ./cmd -word=NewWord