2

How do I make sure every flag argument was set from the command line? I would like to do this without checking each flag name specifically, and would like to instead check all flags dynamically.

Here is my code, main.go:

package main

import (
    "fmt"
    "flag"
)

func main() {
    x := flag.String("x", "", "x flag")
    y := flag.String("y", "", "y flag")
    flag.Parse()
}

I run it, for example, like this: go run main.go -x hello

Noam Hacker
  • 4,671
  • 7
  • 34
  • 55

1 Answers1

4

This can be achieved using the VisitAll function.

VisitAll visits the command-line flags in lexicographical order, calling fn for each. It visits all flags, even those not set.

Sample code (add after flag.Parse()):

flag.VisitAll(func (f *flag.Flag) {
    if f.Value.String()=="" {
        fmt.Println(f.Name, "not set!")
    }
})
Noam Hacker
  • 4,671
  • 7
  • 34
  • 55