go

How to specify positional arguments with the flag package in Golang?


Sometimes I want to pass an argument on the command line with no name, say a command like wc, which takes a filename as input:

wc filename.txt

With the flag package, it looks like every flag has to be given a name, with a default value if unspecified.

filename := flag.String("filename", "foo.txt", "Which file to count the words for")

However I don't want a default value, I want the program to exit with an error code if an argument is not specified. How would I add a required argument to a Go binary?

I would also like to be able to parse arguments with type information, so just checking the Args() directly doesn't quite do it.


Solution

  • You just have to check flag.NArg().

    From https://golang.org/pkg/flag/#NArg:

    NArg is the number of arguments remaining after flags have been processed.

    flag.Parse()
    if flag.NArg() == 0 { 
        flag.Usage()
        os.Exit(1)
    }