Search code examples
gogo-flag

Check if all flags were set (no flags blank)


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


Solution

  • 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!")
        }
    })