Golang flag positional arguments

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.

You just have to check flag.NArg().

From flag - The Go Programming Language

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

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