Using the flag package involves three steps: First, define variables to capture flag values, then define the flags your Go application will use, and finally, parse the flags provided to the application upon execution.
Command-line flags Bool() , flag.Int() , etc. After you've defined your flags, you need to call flag. Parse() . This call will execute command-line parsing and will let you use the flags.
This flag. String function returns a string pointer (not a string value); we'll see how to use this pointer below. This declares numb and fork flags, using a similar approach to the word flag. It's also possible to declare an option that uses an existing var declared elsewhere in the program.
Command-line programs often accept flags or options from users to customize the command's execution. Flags are key-value pairs that are added after the command name while running the command. Go lets you accept command line flags using the flags package from the standard library.
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)
}
You can also use the flag.Narg() function to ensure you have the required number of positional arguments, though I don't know what it gives you over len(flag.Args())
if flag.NArg() < minArgs {
// do something
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With